the blog for developers

Java Interview Question: Synchronized

I’ve written already about Java Interview Questions here, here and here. Another question I sometimes ask is about Javas synchronized keyword.

Can you tell me in which different ways one can use synchronized in Java and which are the pros and cons?

There are two ways to use synchronized, as a method modifier and as a code block:

public synchronized void doSomething()


synchronized(semaphore) {

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.

Synchronized methods

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

Synchronized blocks

The advantages of using a synchronized block:

  • 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?

About the author

stephan Stephan Schmidt has been working with internet technologies for the last 20 years. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own. You can find him on Google +

Discuss on Hacker News Vote on HN