Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization on "reference" or on instance

Tags:

Consider the following code:

public class Foo {
  private static final Object LOCK = new Object();
  private Object _lockRef1 = LOCK;
  private Object _lockRef2 = LOCK;
  private int _indx = 0;

  public void dec() {
    synchronized(_lockRef1) {
      _indx--;
    }
  }

  public void inc() {
    synchronized(_lockRef2) {
      _indx++;
    }
  }
}

Is call to methods dec() and inc() threadsafe? On the one hand these methods are synchronized on two different instances _lockRef1 and _lockRef2. On the other hand, these instances "point" on the same object LOCK...

like image 624
Lopotun Avatar asked Dec 14 '09 11:12

Lopotun


People also ask

When should synchronization be used?

Synchronization is usually needed when you are sharing data between multiple invocations and there is a possibility that the data would be modified resulting in inconsistency. If the data is read-only then you dont need to synchronize. In the code snippet above, there is no data that is being shared.

Which is more preferred synchronized method or synchronized block?

In other words, the synchronized method increases the waiting time, whereas synchronized block has an advantage over the method as its scope is limited and smaller than the method.

How many threads per instance can execute inside a synchronized instance method?

Only one thread per instance can execute inside a synchronized instance method.


1 Answers

They're not "synchronized on two different instances" - just because you use two different variables doesn't mean there are two different instances. You've got several variables each of which will have the same value - a reference to the single instance of java.lang.Object.

So yes, this is thread-safe. Of course you shouldn't write code like this in terms of readability, but assuming you're just trying to understand what happens, it's fine.

like image 117
Jon Skeet Avatar answered Oct 25 '22 04:10

Jon Skeet