1 32 package net.sf.retrotranslator.runtime.java.lang; 33 34 import junit.framework.*; 35 import java.util.concurrent.*; 36 37 40 public class ThreadLocal_TestCase extends TestCase { 41 42 private ExecutorService service; 43 44 protected void setUp() throws Exception { 45 super.setUp(); 46 service = Executors.newSingleThreadExecutor(); 47 } 48 49 protected void tearDown() throws Exception { 50 service.shutdown(); 51 super.tearDown(); 52 } 53 54 private void execute(Runnable runnable) throws Exception { 55 try { 56 service.submit(runnable).get(); 57 } catch (ExecutionException e) { 58 Throwable cause = e.getCause(); 59 if (cause instanceof Exception ) throw (Exception ) cause; 60 if (cause instanceof Error ) throw (Error ) cause; 61 throw e; 62 } 63 } 64 65 public void test() throws Exception { 66 final ThreadLocal <String > threadLocal = new ThreadLocal <String >() { 67 protected String initialValue() { 68 return "a"; 69 } 70 }; 71 assertEquals("a", threadLocal.get()); 72 threadLocal.set("b"); 73 execute(new Runnable () { 74 public void run() { 75 assertEquals("a", threadLocal.get()); 76 threadLocal.set("x"); 77 assertEquals("x", threadLocal.get()); 78 } 79 }); 80 assertEquals("b", threadLocal.get()); 81 threadLocal.set(null); 82 assertNull(threadLocal.get()); 83 threadLocal.remove(); 84 execute(new Runnable () { 85 public void run() { 86 assertEquals("x", threadLocal.get()); 87 threadLocal.set("y"); 88 } 89 }); 90 assertEquals("a", threadLocal.get()); 91 execute(new Runnable () { 92 public void run() { 93 assertEquals("y", threadLocal.get()); 94 threadLocal.set(null); 95 threadLocal.remove(); 96 assertEquals("a", threadLocal.get()); 97 threadLocal.remove(); 98 threadLocal.set(null); 99 assertNull(threadLocal.get()); 100 } 101 }); 102 } 103 104 105 } | Popular Tags |