File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Conditions in Synchronized Blocks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Reply locked New topic

Conditions in Synchronized Blocks

Keith Jones
Ranch Hand

Joined: Oct 30, 2006
Posts: 105
I have heard it said that one should never use an if condition in a synchronized block (and should replace it with a while) because if a thread slices out in the middle of executing the if condition then the condition that it was attempting to evaluate before being sliced out could be different when that thread slices back in because another thread could have changed it and this a problem because an if (unlike a while) continues execution from where it left off.

I have done this with my code and have found that it produces peculiar looking code. For example:

In this code will there be an endless stream of exceptions thrown? Are there cases when we can't just simply change 'if' to 'while'?


SCJP 1.4
Brian Kelly
Ranch Hand

Joined: Jan 04, 2007
Posts: 54
Use a "break".

But it won't be a problem if your condition is related to your "lock" like:

synchronized(lock) {
if (lock.isAlreadyLocked()) {
throw new Exception();

If your condition has nothing to do with "lock" then you might be synch on the wrong object...

Keith Jones
Ranch Hand

Joined: Oct 30, 2006
Posts: 105
Well my lock is on the map of locked records against thread hashcodes and the comdition is to check whether a record exists or is deleted in the database. The spec says that if a record is deleted or does not exist then we should throw a RecordNotFoundException. I put this code inside a synchronized block just to be on the safe side. It was an if statement but I have heard it should be a while statement so i changed it.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Please don't post the same question in more than one forum. Followups go here. Thanks.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Conditions in Synchronized Blocks
It's not a secret anymore!