Win a copy of Design for the Mind this week in the Design forum!
    Bookmark Topic Watch Topic
  • New Topic

Conditions in Synchronized Blocks

 
Keith Jones
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Report post to moderator
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'?

Cheers
 
Brian Kelly
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 105
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Report post to moderator
Please don't post the same question in more than one forum. Followups go here. Thanks.
 
    Bookmark Topic Watch Topic
  • New Topic