Conditionally define synchronized block

user5047085 :

Say I have a method:

public void run(){
  synchronized(this.foo){

 }
}

but sometimes when I run this method, I don't need to synchronize on anything.

What is a good pattern to conditionally synchronize on something? The only pattern I can think of is a callback, something like this:

public void conditionalSync(Runnable r){
   if(bar){
      r.run();
      return;
   }

  synchronized(this.foo){
     r.run();
  }
}

public void run(){
  this.conditionalSync(()->{


  });
}

is there another way to do it, without a callback?

xingbin :

Instead of synchronized keyword, maybe you can use ReentrantLock(which is more flexible and powerful).

Example:

ReentrantLock lock = ...;


public void run(){
    if (bar) {
        lock.lock();
    }

    try {
        // do something

    } finally {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36974&siteId=1