+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

vijaygarg1inita10c404

master
2.2 KiB87 linesraw
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  
7  ReentrantLock enqLock, deqLock;
8  Condition notEmptyCondition, notFullCondition;
9  AtomicInteger size;
10  Entry head;
11  Entry tail;
12  int capacity;
13  public TwoLockQueue(int capacity) {
14    this.capacity = capacity;
15    this.head = new Entry(null);
16    this.tail = head;
17    this.size = new AtomicInteger(capacity);
18    this.enqLock = new ReentrantLock();
19    this.notFullCondition = enqLock.newCondition();
20    this.deqLock = new ReentrantLock();
21    this.notEmptyCondition = deqLock.newCondition();
22  }
23  public Object deq() {
24    Object result;
25    boolean mustWakeEnqueuers = true;
26    deqLock.lock();
27    try {
28      while (size.get() == capacity) {
29        try {
30          notEmptyCondition.await();
31        } catch (InterruptedException ex) {}
32      }
33      result = head.next.value;
34      head = head.next;
35      if (size.getAndIncrement() == 0) {
36        mustWakeEnqueuers = true;
37      }
38    } finally {
39      deqLock.unlock();
40    }
41    if (mustWakeEnqueuers) {
42      enqLock.lock();
43      try {
44        notFullCondition.signalAll();
45      } finally {
46        enqLock.unlock();
47      }
48    }
49    return result;
50  }
51  public void enq(Object x) {
52    if (x == null) throw new NullPointerException();
53    boolean mustWakeDequeuers = false;
54    enqLock.lock();
55    try {
56      while (size.get() == 0) {
57        try {
58          notFullCondition.await();
59        } catch (InterruptedException e) {}
60      }
61      Entry e = new Entry(x);
62      tail.next = e;
63      tail = e;
64      if (size.getAndDecrement() == capacity) {
65        mustWakeDequeuers = true;
66      }
67    } finally {
68      enqLock.unlock();
69    }
70    if (mustWakeDequeuers) {
71      deqLock.lock();
72      try {
73        notEmptyCondition.signalAll();
74      } finally {
75        deqLock.unlock();
76      }
77    }
78  }
79  protected class Entry {
80    public Object value;
81    public Entry next;
82    public Entry(Object x) {
83      value = x;
84      next = null;
85    }
86  }
87}