01: /*
02: * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
03: * Copyright (C) 2005 - Javolution (http://javolution.org/)
04: * All rights reserved.
05: *
06: * Permission to use, copy, modify, and distribute this software is
07: * freely granted, provided that this notice is preserved.
08: */
09: 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 get() {
25: FastMap localMap = getLocalMap();
26: Object 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 value) {
35: getLocalMap().put(this , value);
36: }
37:
38: public void remove() {
39: getLocalMap().remove(this );
40: }
41:
42: protected Object 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 thread = (Thread) 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: }
|