Forums Register Login

NX: 'if" use in sync blocks

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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
Why does your bag say "bombs"? The reason I ask is that my bag says "tiny ads" and it has stuff like this:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 670 times.
Similar Threads
NX: RandomAccessFile / Singleton DataSchema
Deadlock on the thin cleint
Passed SCJD
Lock design
pls validate my locking strategy - all inputs are g8ly appreciated. (URLyBird)
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 19, 2024 05:06:18.