Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "synchronized if" statement?

Tags:

java

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?

like image 365
Hobbyist Avatar asked Sep 14 '25 14:09

Hobbyist


1 Answers

  1. 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";
    }
    
  2. 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)

like image 135
Paizo Avatar answered Sep 17 '25 05:09

Paizo