1 9 package j2me.lang; 10 11 import javolution.util.FastMap; 12 13 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 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 } | Popular Tags |