Consider the following multithreaded code written in Java:
Shared variables:
boolean n; // non-volatile
volatile boolean v; // volatile
Thread 1:
v = true;
System.out.println("n=" + n);
Thread 2:
n = true;
System.out.println("v=" + v);
Assume initially n = v = false.
Now:
v=false imply the output of n=true?n were volatile?n were java.util.List (so that n = true becomes n.add("something") and the output n=true transforms into ["something"])?v were AtomicBoolean and all reads of and writes to it performed with the compareAndSet semantic?Could you argue your position according to the Java Memory Model?
UPD: Please treat System.out.println("n=" + n) as just a read of n. The same for v.
UPD2: Could you provide some analysis of the 1st and 4th case as it shown in JSR-133 sec. 8?
You have two factors involved here.
volatile field, butsynchronized call to System.out.println This acts read/write barrierIn both threads you are performing a write and a read. A write barrier doesn't guarantee a read barrier.
Does the output of v=false imply the output of n=true?
If you see v=false you might see a n=false and visa versa
What would change if n were volatile?
Not really, you might see a change in behaviour depending on the architecture you are running on, however you can still see indeterminate behaviour of some machines.
What would change if n were java.util.List
The main change is you are replacing a write barrier e.g. n = true with a read barrier n.method This means you no longer have a write barrier (except the call to the synchronized method)
Doing this means there is more reasons for consistency between threads to fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With