+/EE360P
distributed systems
git clone https://git.julia.blue/+/EE360P
fd8db29
master
1import java .util .concurrent .atomic .AtomicInteger ; 2import java .util .concurrent .locks .Condition ; 3import java .util .concurrent .locks .ReentrantLock ; 4 5public class TwoLockQueue {//adapted from Herlihy's 6 7ReentrantLock enqLock ,deqLock ; 8Condition notEmptyCondition ,notFullCondition ; 9AtomicInteger size ; 10Entry head ; 11Entry tail ; 12int capacity ; 13public TwoLockQueue (int capacity ) { 14this .capacity =capacity ; 15this .head =new Entry (null ); 16this .tail =head ; 17this .size =new AtomicInteger (capacity ); 18this .enqLock =new ReentrantLock (); 19this .notFullCondition =enqLock .newCondition (); 20this .deqLock =new ReentrantLock (); 21this .notEmptyCondition =deqLock .newCondition (); 22 } 23public Object deq () { 24Object result ; 25boolean mustWakeEnqueuers =true ; 26deqLock .lock (); 27try { 28while (size .get () ==capacity ) { 29try { 30notEmptyCondition .await (); 31 }catch (InterruptedException ex ) {} 32 } 33result =head .next .value ; 34head =head .next ; 35if (size .getAndIncrement () ==0 ) { 36mustWakeEnqueuers =true ; 37 } 38 }finally { 39deqLock .unlock (); 40 } 41if (mustWakeEnqueuers ) { 42enqLock .lock (); 43try { 44notFullCondition .signalAll (); 45 }finally { 46enqLock .unlock (); 47 } 48 } 49return result ; 50 } 51public void enq (Object x ) { 52if (x ==null )throw new NullPointerException (); 53boolean mustWakeDequeuers =false ; 54enqLock .lock (); 55try { 56while (size .get () ==0 ) { 57try { 58notFullCondition .await (); 59 }catch (InterruptedException e ) {} 60 } 61Entry e =new Entry (x ); 62tail .next =e ; 63tail =e ; 64if (size .getAndDecrement () ==capacity ) { 65mustWakeDequeuers =true ; 66 } 67 }finally { 68enqLock .unlock (); 69 } 70if (mustWakeDequeuers ) { 71deqLock .lock (); 72try { 73notEmptyCondition .signalAll (); 74 }finally { 75deqLock .unlock (); 76 } 77 } 78 } 79protected class Entry { 80public Object value ; 81public Entry next ; 82public Entry (Object x ) { 83value =x ; 84next =null ; 85 } 86 } 87}