I'm trying to find a clean way to write out a method that may, or may not be wrapped in a synchornized
lock based on a boolean. However the only way I can find to do this is very ugly.
boolean lock = true;
void remove(Object o) {
if(lock) {
synchornized(this) {
// remove o
}
} else {
// remove o
}
}
However, I'm wondering if there's a nicer way to do this, perhaps a "Synchronize if" type of statement?
You can use AtomicBoolean
:
private final AtomicBoolean lock = new AtomicBoolean(false);
...
// compare if it is false and set it to true, no synchronized needed
if (lock.compareAndSet(false, true)) {
statusMessage = "lock acquired";
} else {
statusMessage = "I'm already locked";
}
or define the method as synchronized
.
your current check for the lock is not in a synchronized block:
if(lock) {
synchronized(this) {
Hence 2 threads may pass this check before you set it to false, the real semaphore there is synchronized(this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With