-
Notifications
You must be signed in to change notification settings - Fork 5
/
ThreadSafeQueue.java
executable file
·108 lines (96 loc) · 1.92 KB
/
ThreadSafeQueue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package com.vee.algorithms.concurrency;
public class ThreadSafeQueue {
private final Object lock = new Object();
private static int BUFFERSIZE = 6;
String[] buffer;
private int front = -1;
private int rear = -1;
private int size = 0;
private int maxSize;
public ThreadSafeQueue() {
this(BUFFERSIZE);
}
public ThreadSafeQueue(int maxSize) {
this.maxSize = maxSize;
buffer = new String[maxSize];
}
public boolean isEmpty() {
if(size == 0)
return true;
return false;
}
public boolean isFull() {
if(size == maxSize)
return true;
return false;
}
public void enqueue(String s) {
synchronized (lock) {
while (isFull()) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
if(isEmpty())
front = 0;
if(!isFull()) {
rear = (rear + 1)% maxSize;
buffer[rear] = s;
size++;
}
lock.notifyAll();
}
}
public String dequeue() {
synchronized (lock) {
while (isEmpty()) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
String top = buffer[front];
size--;
buffer[front] = null;
front = (front + 1) % maxSize;
lock.notifyAll();
return top;
}
}
public int size() {
return size;
}
/* Not a thread safe operation and expensive to make threadsafe*/
public void display() {
System.out.println(String.format("Size= %d, Front= %d, Rear = %d" , size,front,rear));
int count = 0;
if(isEmpty())
return;
for (int i = front; ;i = (i+1)% maxSize) {
System.out.println(buffer[i]);
if(count++ == size-1)
break;
}
}
public static void main(String[] args) {
ThreadSafeQueue q = new ThreadSafeQueue(10);
q.enqueue("a");
q.enqueue("b");
q.enqueue("c");
q.enqueue("d");
q.enqueue("e");
q.enqueue("f");
q.display();
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
q.display();
q.enqueue("g");
q.dequeue();
q.enqueue("h");
q.dequeue();
q.display();
}
}