Java Interview Question: Synchronized
Can you tell me in which different ways one can use
synchronizedin Java and which are the pros and cons?
public synchronized void doSomething()
At first I let the candidate explain the differences and how and when to use each way. Then I ask about advantages and disadvantages of each method.
Many people think there are no advantages for the method modifier, but here they are:
- Synchronization startegy is explicit and documented in the API
- Method is coarse, so there are less chances for deadlocks – though you can still easily create one
The disadvantages of method synchronization:
- Coarse locking is not performant
- Can easily lead to too much synchronization, usually developers have no clear overall locking strategy when using synchronized which leads to too many locks
The advantages of using a
- Fine tuning on what to lock on
- Smaller code blocks than methods for better performance
The disadvantages are:
- Can easily hold more than one lock (nested synchronized blocks), so deadlocks are easier
- Synchronization strategy not documented, blocks are not composable so you need to look into method
You can find another discussion on methods vs. blocks on StackOverflow.
Further concurrency discussion
I then usually go into a deeper discussion on what the
synchronized block can sync. You can use classes, object instances, object attributes or “this”. Each of these usages has pros and cons, mainly about the scope of the synchronized block and the strategy between concurrent threads.
If the candidate steers through all of this, I go deeper into concurrency and ask about better methods in Java for concurrent programming – what he knows and what he has used and why. This includes the data structures in
java.util.concurrent, message passing and actors, STM or fork/join with work stealing.
Hope you know your concurrency and what do you think are the pros and cons of different synchronization constructs in Java?