java - Is it possible to "synchronized if" statement? -
i'm trying find clean way write out method may, or may not wrapped in synchornized
lock based on boolean. way can find ugly.
boolean lock = true; void remove(object o) { if(lock) { synchornized(this) { // remove o } } else { // remove o } }
however, i'm wondering if there's nicer way this, perhaps "synchronize if" type of statement?
you can use
atomicboolean
:private final atomicboolean lock = new atomicboolean(false); ... // compare if false , set true, no synchronized needed if (lock.compareandset(false, true)) { statusmessage = "lock acquired"; } else { statusmessage = "i'm locked"; }
or define method
synchronized
.
your current check lock not in synchronized block:
if(lock) { synchronized(this) {
hence 2 threads may pass check before set false, real semaphore there synchronized(this)
Comments
Post a Comment