Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what situations could an empty synchronized block achieve correct threading semantics?

I was looking through a Findbugs report on my code base and one of the patterns that was triggered was for an empty synchronzied block (i.e. synchronized (var) {}). The documentation says:

Empty synchronized blocks are far more subtle and hard to use correctly than most people recognize, and empty synchronized blocks are almost never a better solution than less contrived solutions.

In my case it occurred because the contents of the block had been commented out, but the synchronized statement was still there. In what situations could an empty synchronized block achieve correct threading semantics?

like image 965
sk. Avatar asked Mar 26 '09 16:03

sk.


People also ask

What is purpose of synchronized block in multithreading?

A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a synchronized block is smaller than the synchronized method.

What is the advantage of synchronized block over synchronized method?

Synchronized blocks provide granular control over a lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand, the synchronized method always locks either on the current object represented by this keyword or class level lock, if it's a static synchronized method.

What would you do if threads throw exceptions within a synchronized block?

Other threads will be able to continue synchronizing, and calling wait and notify. If the thread with the exception is holding some critical program logic resource, you may need to use try-finally to ensure it is released.

What will happen if synchronized method is called by two threads?

Can two threads call two different synchronized instance methods of an Object? No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.


1 Answers

An empty synchronized block will wait until nobody else is using that monitor.

That may be what you want, but because you haven't protected the subsequent code in the synchronized block, nothing is stopping somebody else from modifying what ever it was you were waiting for while you run the subsequent code. That's almost never what you want.

like image 77
Paul Tomblin Avatar answered Sep 18 '22 21:09

Paul Tomblin