-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCustomConcurrentStack.java
53 lines (46 loc) · 1.26 KB
/
CustomConcurrentStack.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
package by.andd3dfx.multithreading.stack;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Implement custom stack with multithreading support without using blocking operations
*
* @see <a href="https://youtu.be/R6yUAA82_3Y">Video solution</a>
*/
public class CustomConcurrentStack<T> {
private Deque<T> deque = new ArrayDeque<>();
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public T push(T element) {
lock.writeLock().lock();
try {
deque.push(element);
return element;
} finally {
lock.writeLock().unlock();
}
}
public T pop() {
lock.writeLock().lock();
try {
return deque.pop();
} finally {
lock.writeLock().unlock();
}
}
public T peek() {
lock.readLock().lock();
try {
return deque.peek();
} finally {
lock.readLock().unlock();
}
}
public boolean isEmpty() {
lock.readLock().lock();
try {
return deque.isEmpty();
} finally {
lock.readLock().unlock();
}
}
}