1 4 package org.oddjob.util; 5 6 import java.util.ArrayList ; 7 import java.util.HashMap ; 8 import java.util.Iterator ; 9 import java.util.List ; 10 import java.util.Map ; 11 12 import org.apache.log4j.Logger; 13 import org.oddjob.Stoppable; 14 15 19 public class ThreadManager { 20 private static final Logger logger = Logger.getLogger(ThreadManager.class); 21 22 23 private volatile ClassLoader classLoader; 24 25 26 private final Map activeThreads = new HashMap (); 27 28 32 public ThreadManager() { 33 classLoader = Thread.currentThread().getContextClassLoader(); 34 } 35 36 43 public void run(final Runnable runnable, final String description, 44 final ClassLoader classLoader) { 45 Runnable wrapper = new Runnable () { 46 public void run() { 47 ClassLoader existing = Thread.currentThread().getContextClassLoader(); 48 try { 49 if (classLoader != null) { 50 Thread.currentThread().setContextClassLoader(classLoader); 51 } 52 runnable.run(); 53 } 54 catch (Throwable t) { 55 logger.error("Failed running [" + description + "]", t); 56 } 57 finally { 58 synchronized (activeThreads) { 59 activeThreads.remove(Thread.currentThread()); 60 } 61 Thread.currentThread().setContextClassLoader(existing); 64 } 65 } 66 }; 67 Thread t = new Thread (wrapper); 68 synchronized (activeThreads) { 69 activeThreads.put(t, new Remember(description, runnable)); 70 } 71 t.start(); 72 } 73 74 80 public void run(Runnable runnable, String description) { 81 run(runnable, description, classLoader); 82 } 83 84 92 public String [] activeDescriptions() { 93 List results = new ArrayList (); 94 synchronized (activeThreads) { 95 for (Iterator it = activeThreads.entrySet().iterator(); it.hasNext(); ) { 96 Map.Entry entry = (Map.Entry ) it.next(); 97 Thread t = (Thread ) entry.getKey(); 98 if (!Thread.currentThread().equals(t)) { 99 results.add( ((Remember)entry.getValue()).description ); 100 } 101 } 102 return (String []) results.toArray(new String [0]); 103 104 } 105 } 106 107 public String toString() { 108 return "ThreadManager: " + activeThreads.size() + " active threads."; 109 } 110 111 114 public ClassLoader getClassLoader() { 115 return classLoader; 116 } 117 120 public void setClassLoader(ClassLoader classLoader) { 121 this.classLoader = classLoader; 122 } 123 124 public void stopAll() { 125 synchronized (activeThreads) { 126 for (Iterator it = activeThreads.entrySet().iterator(); it.hasNext(); ) { 127 Map.Entry entry = (Map.Entry ) it.next(); 128 Thread t = (Thread ) entry.getKey(); 129 Remember r = (Remember) entry.getValue(); 130 if (r.runnable instanceof Stoppable) { 131 ((Stoppable) r.runnable).stop(); 132 } 133 else { 134 if (!Thread.currentThread().equals(t)) { 135 t.interrupt(); 136 } 137 } 138 } 139 } 140 } 141 142 class Remember { 143 private final String description; 144 private final Runnable runnable; 145 146 Remember(String description, Runnable runnable) { 147 this.description = description; 148 this.runnable = runnable; 149 } 150 } 151 } 152 | Popular Tags |