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?

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

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -