+/EE360P

distributed systems

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

vijaygarg1add stack and queuecccc41d

master
2.4 KiB106 linesraw
1import java.util.concurrent.locks.Lock;
2import java.util.concurrent.locks.ReentrantLock;
3public class ConcLockList { //Adapted from Herlihy's Book
4  private Node head;
5  public ConcLockList() {
6    head      = new Node(Integer.MIN_VALUE);
7    head.next = new Node(Integer.MAX_VALUE);
8  }
9  public boolean insert(Object item) {
10    int key = item.hashCode();
11    head.lock();
12    Node pred = head;
13    try {
14      Node curr = pred.next;
15      curr.lock();
16      try {
17        while (curr.key < key) {
18          pred.unlock();
19          pred = curr;
20          curr = curr.next;
21          curr.lock();
22        }
23        if (curr.key == key) {
24          return false;
25        }
26        Node newNode = new Node(item);
27        newNode.next = curr;
28        pred.next = newNode;
29        return true;
30      } finally {
31        curr.unlock();
32      }
33    } finally {
34      pred.unlock();
35    }
36  }
37  public boolean remove(Object item) {
38    Node pred = null, curr = null;
39    int key = item.hashCode();
40    head.lock();
41    try {
42      pred = head;
43      curr = pred.next;
44      curr.lock();
45      try {
46        while (curr.key < key) {
47          pred.unlock();
48          pred = curr;
49          curr = curr.next;
50          curr.lock();
51        }
52        if (curr.key == key) {
53          pred.next = curr.next;
54          return true;
55        }
56        return false;
57      } finally {
58        curr.unlock();
59      }
60    } finally {
61      pred.unlock();
62    }
63  }
64  public boolean contains(Object item) {
65    Node last = null, pred = null, curr = null;
66    int key = item.hashCode();
67    head.lock();
68    try {
69      pred = head;
70      curr = pred.next;
71      curr.lock();
72      try {
73        while (curr.key < key) {
74          pred.unlock();
75          pred = curr;
76          curr = curr.next;
77          curr.lock();
78        }
79        return (curr.key == key);
80      } finally {
81        curr.unlock();
82      }
83    } finally {
84      pred.unlock();
85    }
86  }
87  private class Node {
88    Object item;
89    int key;
90    Node next;
91    Lock lock;
92    Node(Object item) {
93      this.item = item;
94      this.key = item.hashCode();
95      this.lock = new ReentrantLock();
96    }
97    Node(int key) {
98      this.item = null;
99      this.key = key;
100      this.lock = new ReentrantLock();
101    }
102    void lock() {lock.lock();}
103    void unlock() {lock.unlock();}
104  }
105}
106