KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > controller > ThreadLocalStack


1 package com.tonbeller.wcf.controller;
2
3 import java.util.Stack JavaDoc;
4
5 /**
6  * Maintains a stack in a ThreadLocal. If the stack is empty, the ThreadLocal is cleared,
7  * so there is no memory leak.
8  * <p/>
9  * Implementation note: its not necessary to synchronize because every Thread
10  * uses its own instance of the java.util.Stack.
11  *
12  * @author av
13  * @since Sep 12, 2005
14  */

15 class ThreadLocalStack {
16   ThreadLocal JavaDoc tl = new ThreadLocal JavaDoc();
17
18   public void push(Object JavaDoc obj) {
19     Stack JavaDoc stack = (Stack JavaDoc) tl.get();
20     if (stack == null) {
21       stack = new Stack JavaDoc();
22       tl.set(stack);
23     }
24     stack.push(obj);
25   }
26
27   /**
28    * @param failIfEmpty if true, an EmptyThreadLocalStackException is thrown
29    * when called on an empty stack. If false, null is returned for an empty stack.
30    */

31   public Object JavaDoc peek(boolean failIfEmpty) throws EmptyThreadLocalStackException {
32     Stack JavaDoc stack = (Stack JavaDoc) tl.get();
33     if (stack == null || stack.isEmpty()) {
34       if (failIfEmpty)
35         throw new EmptyThreadLocalStackException();
36       return null;
37     }
38     return stack.peek();
39   }
40
41
42   public void pop() {
43     Stack JavaDoc stack = (Stack JavaDoc) tl.get();
44     if (stack == null || stack.isEmpty())
45       throw new EmptyThreadLocalStackException();
46     stack.pop();
47     if (stack.isEmpty())
48       tl.set(null);
49   }
50
51 }
52
Popular Tags