Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing on an object in java, then changing the value of the synchronized-on variable

Tags:

I came across a code like this

synchronized(obj) {     obj = new Object();  } 

Something does not feel right about this , I am unable to explain, Is this piece of code OK or there is something really wrong in it, please point it out. Thanks

like image 215
codemon Avatar asked Jul 15 '11 18:07

codemon


People also ask

Can we use synchronized with variable in Java?

You can not apply java synchronized keyword with the variables. Don't synchronize on the non-final field on synchronized block because the reference to the non-final field may change anytime and then different threads might synchronize on different objects i.e. no synchronization at all.

Do synchronized methods synchronize on the object or the class?

Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.

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.


1 Answers

It's probably not what you want to do. You're synchronizing on an object that you're no longer holding a reference to. Consider another thread running this method: they may enter and try to hit the lock at the moment after the reference to obj has been updated to point to the new object. At that point, they're synchronizing on a different object than the first thread. This is probably not what you're expecting.

Unless you have a good reason not to, you probably want to synchronize on a final Object (for visibility's sake.) In this case, you would probably want to use a separate lock variable. For example:

class Foo {     private final Object lock = new Object();     private Object obj;      public void method()     {         synchronized(lock)         {             obj = new Object();         }     } } 
like image 77
Edward Thomson Avatar answered Oct 05 '22 12:10

Edward Thomson