volatile doesn't work as intended

Remi Forax forax at univ-mlv.fr
Thu Sep 26 10:17:37 UTC 2019


Hi guys,
it seems that volatile doesn't work as it should with an inline value.
a volatile field should force the field to be not flattened but the code below still throw an AssertionError
(sometimes, you are to run the program several times).

regards,
Rémi

public class ValueTearing {
	@__inline__
  static class Value {
		private int x;
		private int y;
		
		public Value(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
	
  public static void main(String[] args) {
		var box = new Object() { volatile Value shared; };
		var zero = new Value(0, 0);
		var one = new Value(1, 1);
		new Thread(() -> {
			for(;;) {
				box.shared = zero;
			}
	  }).start();
		new Thread(() -> {
			for(;;) {
			  box.shared = one;
			}
	  }).start();
		for(;;) {
			var value = box.shared;
			if (value.x != value.y) {
				throw new AssertionError("oops " + value);
			}
		}
	}
}



More information about the valhalla-dev mailing list