• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NX: 'if" use in sync blocks

 
Hugh Johns
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it a general rule to avoid using if statements in a synchronized block,
and use a while instead to prevent problems associated with slicing in and out of threads.
I have coded an unlock method which uses if statements to check preconditions as the following psudo code outlines...
note: recordsLocked is a hashmap containing record number/lock pairs
synchronized( recordsLocked )
{
// Check if lock exists for this record
if(! recordExistsInHash )
{
throw ...
}
// Check if client has correct lock
if(! recordMatchCookie )
{
throw ...
}
// Has lock, now unlock record
if( recordExistsInHash && recordMatchCookie )
{
...
}
}
I am using the if statements to check preconditions, which either pass of fail when the method is called, and since it holds the lock on the recordsLocked map, these conditions should not change over slicing ?
Is this bad coding practice?.
Regards
Hugh
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 12007
215
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hugh,
I cannot see any advantage to changing to while statements in this case.
Using while statements would only be required if any of the conditions could change.
Regards, Andrew
 
Ulrich Heeger
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hugh,
I think the advantage of a while-loop in a synchronized block is that if you call the wait-method on the synchronized object, the while-condition will be checked again, when the thread gets notified.
Best,
Ulrich
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the advantage of a while-loop in a synchronized block is that if you call the wait-method on the synchronized object, the while-condition will be checked again, when the thread gets notified.
Yep.
 
Max Habibi
town drunk
( and author)
Sheriff
Posts: 4118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hugh,
The code looks fine, but I�m not sure it fulfills the requirements. Aren't you supposed to wait until you can achieve the lock? I don't see that happening in the code.
M
 
Hugh Johns
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Max
The psudo code is not entirely clear, it describes unlocking, therefore if a lock for the record number exists in the map, and the client holds the correct cookie , then unlock.
I was just confirming it is ok to use 'if' in checking preconditions in a sync block.
Thanks
Hugh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic