Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized Block within Synchronized Method

I'm looking at some code in a third party library that contains a synchronized method, and within this method there is a synchronized block that locks on an instance variable. It's similar to this:

public class Foo {
   final Bar bar = new Bar();

   public synchronized void doSomething() {
       // do something
       synchronized(bar) {
           // update bar
       }
   }
   ...
}

Does this make sense? If so, what benefits are there to having a synchronized statement within a synchronized method?

Given that a synchronized method locks on the entire object, it seems redundant to me. Perhaps this approach makes sense when working with instance variables that are not private?

like image 229
The Gilbert Arenas Dagger Avatar asked Sep 01 '15 18:09

The Gilbert Arenas Dagger


People also ask

Can synchronized blocks can also be used inside of static methods?

Synchronized Blocks in Static MethodsOnly one thread can execute inside any of these two methods at the same time. Had the second synchronized block been synchronized on a different object than MyClass. class , then one thread could execute inside each method at the same time.

Which method is used within synchronized block?

In Java, wait(), notify() and notifyAll() are the important methods that are used in synchronization.

Can synchronized block be nested?

In that kind of scenario both threads will be waiting for each other forever to release lock they are already holding thus creating a deadlock. One synchronized method is called from another synchronized method. See example. There are nested synchronized blocks.

Which is better synchronized block or synchronized method?

synchronized block has better performance as only the critical section is locked but synchronized method has poor performance than block. synchronized block provide granular control over lock but synchronized method lock either on current object represented by this or class level lock.


2 Answers

In your example the method is both locking on the instance of Foo and on the object bar. Other methods may only be locking on the instance of Foo or on the object bar.

So, yes, this makes sense depending on exactly what they are doing. Presumably bar protects some smaller subset of data, and some methods will only need to lock on bar to perform their actions in a thread-safe manner.

What synchronized does

synchronized (on a method, or in a statement) creates a mutual exclusion zone (critical section or, specifically for Java, a reentrant mutex). The "key" for a thread to enter the critical section is the object reference used in the synchronized statement . Only one thread can (recursively) "own" this "key" at one time across all blocks that use the same key; that is, only one thread can enter any block synchronized on a given object reference at one time.

Such a critical section simply prevents the operations (variable read/write) that you do inside the block happening concurrently with any other operations in all other critical sections that lock on the same object reference. (It doesn't automatically protect all variables inside an object).

In Java, such a critical section also creates a happens-before contract.

By example

As a somewhat contrived example :

public class Foo {
    final Bar bar = new Bar();
    
    private int instanceCounter = 0;
    private int barCounter = 0;

    public synchronized void incrementBarCounterIfAllowed() {
        synchronized (bar) {
            if (instanceCounter < 10) barCounter++;
        }
    }

    public synchronized void incrementClassCounter() {
        instanceCounter++;
    }

    public void incrementBarCounter() {
        synchronized (bar) {
            barCounter++;
        }
    }

}

Whether the instance variables are private or not doesn't really matter to whether this approach is applicable. In a single class you can have multiple lock objects, each of which protect their own set of data.

However the risk of doing this is that you have to be very strict with coding conventions to prevent deadlocks by locking two locks in different orders in different places. For example, with the above code if you then do this from somewhere else in the code:

synchronized(myFoo.bar) {
  myFoo.incrementClassCounter();
}

you risk a deadlock with the incrementBarCounterIfAllowed() method

Note that barCounter could be an instance variable for Bar etc etc - I avoided that for the sake of brevity in the code sample.

In the case of synchronized methods, that reference is the reference to the class instance (or to the Class<?> for the class for static methods).

like image 140
Andy Brown Avatar answered Sep 22 '22 17:09

Andy Brown


When you say "synchronized method locks on the entire object", that's not true. Using synchronized only means that threads have to acquire that lock before they can enter the methods or blocks marked as synchronized that use that lock. The default object used as a lock for synchronized on instance methods is this. The default is this.getClass() if you put synchronized on a static method, or you can specify the object to use as a lock. Using synchronized doesn't do anything other than that to make instance fields inaccessible.

You can write a class where some methods or blocks are protected by one lock, some are protected by another lock, and for others you need both locks. Make sure you acquire the locks in the same order or you can cause a deadlock.

like image 22
Nathan Hughes Avatar answered Sep 24 '22 17:09

Nathan Hughes