-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcurrentStack.java
More file actions
61 lines (51 loc) · 1.75 KB
/
ConcurrentStack.java
File metadata and controls
61 lines (51 loc) · 1.75 KB
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
import java.util.concurrent.atomic.AtomicReference;
class Node<T> {
T value;
Node<T> next;
Node(T value) {
this.value = value;
}
}
public class ConcurrentStack<T> {
AtomicReference<Node<T>> top = new AtomicReference<>();
public void push(T value) {
Node<T> newNode = new Node<>(value);
Node<T> oldTop;
do {
oldTop = top.get();
newNode.next = oldTop;
} while (!top.compareAndSet(oldTop, newNode));
}
public T pop() {
Node<T> oldTop;
Node<T> newTop;
do {
oldTop = top.get();
if (oldTop == null) {
return null; // Stack is empty
}
newTop = oldTop.next;
} while (!top.compareAndSet(oldTop, newTop));
return oldTop.value;
}
public boolean isEmpty() {
return top.get() == null;
}
public T peek() {
Node<T> currentTop = top.get();
// Return the value of the top node without removing it
return currentTop != null ? currentTop.value : null;
}
public static void main(String[] args) {
ConcurrentStack<Integer> stack = new ConcurrentStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Top element: " + stack.peek()); // Should print 3
System.out.println("Popped element: " + stack.pop()); // Should print 3
System.out.println("Is stack empty? " + stack.isEmpty()); // Should print false
System.out.println("Popped element: " + stack.pop()); // Should print 2
System.out.println("Popped element: " + stack.pop()); // Should print 1
System.out.println("Is stack empty? " + stack.isEmpty()); // Should print true
}
}