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?
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.
In Java, wait(), notify() and notifyAll() are the important methods that are used in synchronization.
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.
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.
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.
synchronized
doessynchronized
(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.
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).
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.
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