Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Conditions in Synchronized Blocks

 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Please don't post the same question in more than one forum. Followups go here. Thanks.
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic