Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if synchronization variable is reassigned in java?

What happens in the following code? Does the synchronization work? This is an interview question.

class T
{
    public static void main(String args[])
    {
        Object myObject = new Object();
        synchronized (myObject)
        {
            myObject = new Object();
        } // end sync
    }
}
like image 691
codefx Avatar asked Jun 21 '12 08:06

codefx


People also ask

What is the problem with synchronization in Java?

Synchronization can result in hold-wait deadlock where two threads each have the lock of an object, and are trying to acquire the lock of the other thread's object. Synchronization must also be global for a class, and an easy mistake to make is to forget to synchronize a method.

What happens when synchronized object is invoked?

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

What are the risks of synchronization?

Synchronization risk arises from arbitrageur's uncertainty about when other arbitrageurs will start exploiting a common arbitrage opportunity (Abreu and Brunnermeier, 2002 and 2003). The arbitrage opportunity appears when prices move away from fundamental values.

Can volatile replace synchronized?

Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables.


2 Answers

Each time you enter the synchronized block, you synchronize on a different object. Most of the time this will not do anything except confuse you, but there is a small chance that two threads will see the same object and wait.

For this reason any code analysers will give you a warning if you are synchronizing on a field which is not final.

like image 64
Peter Lawrey Avatar answered Oct 05 '22 22:10

Peter Lawrey


It still releases the same monitor that was acquired, but any other code which also locks using myObject (impossible here as it's a local variable, making the synchronization fundamentally pointless) would start to use the new object.

Don't forget that synchronization is applied to objects (or rather, the monitors associated with objects) - not variables. The monitor being acquired/released just depends on the value of the expression when the start of the synchronized block is reached. The expression is not re-evaluated at the end of the synchronized block.

like image 22
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet