eldjon
eldjon

Reputation: 2840

Java multi thread behavior without synchronization

I faced the following question during an interview:

Lets assume a simple class

public class Example{

   private int a;

   public void update(){

      a = some new value;
   }

   public int getA(){

      return a;
   }

}

Now there are 2 threads (T1 and T2) which read and update the a value in the following sequence:

T2 (call update() and the value was set to 1)
T1 (call getA())
T2 (call update() and the value was set to 2)
T1 (call getA())

Is it possible for the last call getA() of thread T1 to return the value 1? If yes under what circumstances?

Upvotes: 3

Views: 533

Answers (1)

erickson
erickson

Reputation: 269667

The last call to to T1 could return 0, 1, or 2. It doesn't really make sense to ask "under what circumstances." Under the circumstance of running this code, basically. The code isn't written for concurrency, so there's no guarantee.

In to guarantee that a a write to a variable by one thread is visible to a read of that variable by another thread, there needs to be a synchronization point between the threads. Otherwise, the JVM is allowed to optimize things in such a way that changes are only visible to the thread that makes them. For example, the writing thread's current notion of the value can be cached on the processor and written to main memory later or never. When another thread reads main memory for the value, it finds the initial value (0), a stale update (1), or the latest update (2).

The easiest fix in this case would be to declare a as a volatile variable. You'd still need some mechanism to ensure that T2 writes before T1 reads, but only in a weak, wall-clock sense.

Upvotes: 2

Related Questions