Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package it.unibo;
- public class VolatilePropagation {
- static volatile int v;
- static int nonVolatile;
- public static void main(final String... args) {
- new Thread(() -> {
- while(true) {
- if (v == Integer.MAX_VALUE) {
- nonVolatile = 0; // nonVolatile gets reset before v
- v = 0;
- }
- nonVolatile++; // nonVolatile is always increased before v
- v++;
- }
- }).start();
- new Thread(() -> {
- while (true) {
- final var v1 = v; // nonVolatile is always read along with v
- final var nv = nonVolatile; // Can't be smaller than v
- if (nv < v1) {
- System.out.println("Unexpected lost update! volatile: " + v1 + " - non volatile: " + nv);
- }
- }
- }).start();
- new Thread(() -> {
- var errors = 0L;
- while (true) {
- final var nv = nonVolatile; // Smaller than v in case of lost update!
- final var v1 = v; // Reversed reading order
- if (nv < v1) {
- errors++;
- if (errors % 1_000_000 == 0) {
- System.out.println("Lost updates in thread 2: " + (errors / 1_000_000) + " millions!");
- }
- }
- }
- }).start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement