KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > j2me > lang > ThreadLocal


1 /*
2  * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
3  * Copyright (C) 2005 - Javolution (http://javolution.org/)
4  * All rights reserved.
5  *
6  * Permission to use, copy, modify, and distribute this software is
7  * freely granted, provided that this notice is preserved.
8  */

9 package j2me.lang;
10
11 import javolution.util.FastMap;
12
13 /**
14  * Clean-room implementation of ThreadLocal for J2ME Platform support.
15  */

16 public class ThreadLocal {
17
18     private static final FastMap THREAD_TO_LOCAL_MAP = new FastMap(256)
19             .setShared(true);
20
21     public ThreadLocal() {
22     }
23
24     public Object JavaDoc get() {
25         FastMap localMap = getLocalMap();
26         Object JavaDoc value = localMap.get(this);
27         if ((value == null) && !(localMap.containsKey(this))) {
28             value = initialValue();
29             localMap.put(this, value);
30         }
31         return value;
32     }
33
34     public void set(Object JavaDoc value) {
35         getLocalMap().put(this, value);
36     }
37
38     public void remove() {
39         getLocalMap().remove(this);
40     }
41
42     protected Object JavaDoc initialValue() {
43         return null;
44     }
45
46     private FastMap getLocalMap() {
47         FastMap localMap = (FastMap) THREAD_TO_LOCAL_MAP.get(Thread
48                 .currentThread());
49         return (localMap != null) ? localMap : newLocalMap();
50     }
51
52     private FastMap newLocalMap() {
53         // First, do some cleanup (remove dead threads).
54
for (FastMap.Entry e = THREAD_TO_LOCAL_MAP.head(), end = THREAD_TO_LOCAL_MAP
55                 .tail(); (e = (FastMap.Entry) e.getNext()) != end;) {
56             Thread JavaDoc thread = (Thread JavaDoc) e.getKey();
57             if (!thread.isAlive()) {
58                 THREAD_TO_LOCAL_MAP.remove(thread);
59             }
60         }
61         FastMap localMap = new FastMap();
62         THREAD_TO_LOCAL_MAP.put(Thread.currentThread(), localMap);
63         return localMap;
64     }
65 }
Popular Tags