1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.xchain.framework.util;
17
18 import java.util.ArrayList;
19 import java.util.LinkedList;
20 import java.util.List;
21 import java.util.NoSuchElementException;
22
23
24
25
26
27
28
29 public class ThreadLocalStack<E>
30 {
31 protected ThreadLocal<LinkedList<E>> stackThreadLocal = new ThreadLocal<LinkedList<E>>();
32
33
34
35
36
37
38 public void push(E item)
39 {
40 LinkedList<E> stack = stackThreadLocal.get();
41
42 if( stack == null ) {
43 stack = new LinkedList<E>();
44 stackThreadLocal.set(stack);
45 }
46
47 stack.addFirst(item);
48 }
49
50
51
52
53
54
55
56 public E pop()
57 {
58 LinkedList<E> stack = stackThreadLocal.get();
59
60 if( stack == null ) {
61 throw new NoSuchElementException("pop() called on an empty stack.");
62 }
63
64
65 if( stack.size() == 1 ) {
66 stackThreadLocal.set(null);
67 }
68
69 return stack.removeFirst();
70 }
71
72
73
74
75
76
77
78 public E peek()
79 {
80 return peek(0);
81 }
82
83
84
85
86
87
88
89
90 public E peek( int depth )
91 {
92 LinkedList<E> stack = stackThreadLocal.get();
93
94 if( stack == null || stack.size() <= depth ) {
95 throw new NoSuchElementException("peek() called on element that is not in the stack.");
96 }
97
98 return stack.get(depth);
99 }
100
101
102
103
104
105
106 public int size()
107 {
108 LinkedList<E> stack = stackThreadLocal.get();
109
110 if( stack == null ) {
111 return 0;
112 }
113
114 return stack.size();
115 }
116
117
118
119
120 public boolean isEmpty()
121 {
122 return stackThreadLocal.get() == null;
123 }
124
125
126
127
128 public void clear()
129 {
130 stackThreadLocal.set(null);
131 }
132
133
134
135
136 public List<E> toList()
137 {
138 if( stackThreadLocal.get() == null ) {
139 return new ArrayList<E>();
140 }
141 else {
142 return new ArrayList<E>(stackThreadLocal.get());
143 }
144 }
145 }