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
}
}
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.
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With