Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMM In Practice

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:

  • Does the output of v=false imply the output of n=true?
  • What would change if n were volatile?
  • What would change if n were java.util.List (so that n = true becomes n.add("something") and the output n=true transforms into ["something"])?
  • UPD3: What if 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?

like image 658
kalaider Avatar asked Mar 24 '26 19:03

kalaider


1 Answers

You have two factors involved here.

  • you have a volatile field, but
  • you have a synchronized call to System.out.println This acts read/write barrier

In 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.

like image 137
Peter Lawrey Avatar answered Mar 27 '26 08:03

Peter Lawrey