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