Take the 2-minute tour ×

Suppose I have the following piece of code

public synchronized void method()
    if(something == null)
        something = new SomeThing();
    //do something 

Now suppose in a multithreaded environment, one thread [Thread 1] enters the method and was preempted just after it executed the new Something(); but before it was able to assign it to something. Then another thread [Thread 2] also tries to call the method. What exactly happens now? What happens to the lock that Thread 1 had acquired? Will Thread 1's steps be rolled back?

share|improve this question
Synchronization is not like a transaction, there is no way to roll something back. How would you roll back if there was a file deleted or a UDP datagram sent in that block? –  Sergey Tachenov Feb 12 '11 at 6:42
add comment

2 Answers 2

up vote 7 down vote accepted

Thread1 did not give up the lock, so it still owns it. When Thread2 prepares to take the lock it will discover that it has to wait and enter a BLOCKED state. The next time the OS schedules Thread1 it will finish execution and release the lock. This allows Thread2 to be schedulable again.

share|improve this answer
add comment

Thread 2 will not be able to enter the method until Thread 1 has exited it because it is synchronized.

Eventually the scheduler will get around to continuing with Thread 1, Thread 1 will execute new Something() and exit the method. Then, Thread 2 will be able to enter the function with the new Something() constructed.

The whole idea of the lock is that Thread 1 does not lose it until it is done with it. Thread 1 unlocks when it exits method(), then Thread 2 is able to acquire it.

share|improve this answer
There is a way to temporarily "lose" a lock in a synchronized block, though. Call Object.wait(). –  Sergey Tachenov Feb 12 '11 at 6:40
add comment

Your Answer


