Advertisement
danysk

Untitled

Jun 15th, 2021
1,143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. package it.unibo;
  2.  
  3. public class VolatilePropagation {
  4.  
  5.     static volatile int v;
  6.     static int nonVolatile;
  7.  
  8.     public static void main(final String... args) {
  9.         new Thread(() -> {
  10.             while(true) {
  11.                 if (v == Integer.MAX_VALUE) {
  12.                     nonVolatile = 0; // nonVolatile gets reset before v
  13.                     v = 0;
  14.                 }
  15.                 nonVolatile++; // nonVolatile is always increased before v
  16.                 v++;
  17.             }
  18.         }).start();
  19.         new Thread(() -> {
  20.             while (true) {
  21.                 final var v1 = v; // nonVolatile is always read along with v
  22.                 final var nv = nonVolatile; // Can't be smaller than v
  23.                 if (nv < v1) {
  24.                     System.out.println("Unexpected lost update! volatile: " + v1 + " - non volatile: " + nv);
  25.                 }
  26.             }
  27.         }).start();
  28.         new Thread(() -> {
  29.             var errors = 0L;
  30.             while (true) {
  31.                 final var nv = nonVolatile; // Smaller than v in case of lost update!
  32.                 final var v1 = v; // Reversed reading order
  33.                 if (nv < v1) {
  34.                     errors++;
  35.                     if (errors % 1_000_000 == 0) {
  36.                         System.out.println("Lost updates in thread 2: " + (errors / 1_000_000) + " millions!");
  37.                     }
  38.                 }
  39.             }
  40.         }).start();
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement