java - Implementing Read-Write Locks with Double-Checked Locking -


i've written java readwritelock readers use double-checked locking acquire write-lock. unsafe (as case dcl lazy-instantiation)?

import java.util.concurrent.atomic.atomicinteger;  public class dclrwlock {     private boolean readeracquiringwritelock = false;     private boolean writerlock = false;     private atomicinteger numreaders = new atomicinteger();      public void readeracquire() throws interruptedexception {         while (!nzandincrement(numreaders)) {             synchronized (this) {                 if (numreaders.get() != 0)                     continue;                 if (readeracquiringwritelock) {                     {                         wait();                     } while (readeracquiringwritelock);                 } else {                     readeracquiringwritelock = true;                     writeracquire();                     readeracquiringwritelock = false;                     assert numreaders.get() == 0;                     numreaders.set(1);                     notifyall();                     break;                 }             }         }     }      public void readerrelease() {         if (numreaders.decrementandget() == 0)             writerrelease();     }      public synchronized void writeracquire() throws interruptedexception {         while (writerlock)             wait();         writerlock = true;     }      public synchronized void writerrelease() {         writerlock = false;         notifyall();     }      // atomically:     // if x nonzero, increments x , returns true     // otherwise returns false     private static boolean nzandincrement(atomicinteger x) {         (;;) {             int val = x.get();             if (val == 0)                 return false;             else if (x.compareandset(val, val + 1))                 return true;         }     } } 

i know java has reentrantreadwritelock. i'm more interested in general question of how determine forms of dcl or aren't safe?

the unsafety of dcl comes when assume because read non-null reference shared variable, writes thread wrote reference visible. in other words, read reference published via datarace , assume things work out fine.

in case don't have data race, race condition on atomic variable. therefore non-safety described above not apply here.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -