1 32 package net.sf.retrotranslator.runtime.java.lang; 33 34 import junit.framework.*; 35 import java.util.concurrent.*; 36 37 40 public class InheritableThreadLocal_TestCase extends TestCase { 41 42 private ExecutorService service; 43 44 private static class TestInheritableThreadLocal extends InheritableThreadLocal <String > { 45 protected String initialValue() { 46 return "a"; 47 } 48 49 protected String childValue(String parentValue) { 50 return "(" + parentValue + ")"; 51 } 52 } 53 54 protected void setUp() throws Exception { 55 super.setUp(); 56 service = Executors.newSingleThreadExecutor(); 57 } 58 59 protected void tearDown() throws Exception { 60 service.shutdown(); 61 super.tearDown(); 62 } 63 64 private void execute(Runnable runnable) throws Exception { 65 try { 66 service.submit(runnable).get(); 67 } catch (ExecutionException e) { 68 Throwable cause = e.getCause(); 69 if (cause instanceof Exception ) throw (Exception ) cause; 70 if (cause instanceof Error ) throw (Error ) cause; 71 throw e; 72 } 73 } 74 75 public void test_Inheritance() throws Exception { 76 final InheritableThreadLocal <String > threadLocal = new TestInheritableThreadLocal(); 77 assertEquals("a", threadLocal.get()); 78 threadLocal.set("b"); 79 execute(new Runnable () { 80 public void run() { 81 assertEquals("(b)", threadLocal.get()); 82 threadLocal.set("x"); 83 } 84 }); 85 assertEquals("b", threadLocal.get()); 86 threadLocal.set(null); 87 assertNull(threadLocal.get()); 88 threadLocal.remove(); 89 execute(new Runnable () { 90 public void run() { 91 assertEquals("x", threadLocal.get()); 92 } 93 }); 94 assertEquals("a", threadLocal.get()); 95 } 96 97 public void test_NoInheritance() throws Exception { 98 final InheritableThreadLocal <String > threadLocal = new TestInheritableThreadLocal(); 99 execute(new Runnable () { 100 public void run() { 101 assertEquals("a", threadLocal.get()); 102 threadLocal.set("x"); 103 } 104 }); 105 assertEquals("a", threadLocal.get()); 106 threadLocal.set("b"); 107 execute(new Runnable () { 108 public void run() { 109 assertEquals("x", threadLocal.get()); 110 } 111 }); 112 assertEquals("b", threadLocal.get()); 113 } 114 115 public void test_Removed() throws Exception { 116 final InheritableThreadLocal <String > threadLocal = new TestInheritableThreadLocal(); 117 assertEquals("a", threadLocal.get()); 118 threadLocal.remove(); 119 execute(new Runnable () { 120 public void run() { 121 assertEquals("a", threadLocal.get()); 122 threadLocal.set("x"); 123 } 124 }); 125 assertEquals("a", threadLocal.get()); 126 threadLocal.set("b"); 127 execute(new Runnable () { 128 public void run() { 129 assertEquals("x", threadLocal.get()); 130 } 131 }); 132 assertEquals("b", threadLocal.get()); 133 } 134 135 } | Popular Tags |