Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading and Synchronization with Thread preemption

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?

like image 852
Swaranga Sarma Avatar asked May 04 '26 04:05

Swaranga Sarma


2 Answers

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.

like image 106
Tim Bender Avatar answered May 05 '26 18:05

Tim Bender


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.

like image 33
Collin Avatar answered May 05 '26 16:05

Collin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!