|
Inhaltsverzeichnis
Zuletzt aktualisiert
|
Confusing unit-of-work with threads http://www.infoq.com/news/2007/09/confusing_uow_with_threads There are two approaches I have taken to share context between threads. Both required a pool of threads to share a ThreadGroup.
Where you have something which is single threaded I associate a single thread pool and a cached (variable sized) pool with the thread group. Single threaded processing requires adding a task the first pool and any which isn't single threaded is added to the second pool. This is the cut down version. You add sub-tasks to either the single pool or the multi threaded pool. The single threaded pool can kick off any number of tasks concurrently and then collect the results with the Future.get() method. Multi-threaded tasks can add sub-task which must run in the same threaded to the single pool. public class MyThreadGroup extends ThreadGroup{ public MyThreadGroup(String name) { super(name); } private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new MyThreadFactory()); private final ExecutorService multiExecutorService = Executors.newCachedThreadPool(new MyThreadFactory()); private final Map<String, Object> values = new ConcurrentHashMap<String, Object>(); public static <T> Future<T> submitSingle(Callable<T> callable) { // add code to check in is not in the single threaded executor already. return getMyThreadGroup().executorService.submit(callable); } public static <T> Future<T> submit(Callable<T> callable) { return getMyThreadGroup().multiExecutorService.submit(callable); } public static Object getValue(String key) { return getMyThreadGroup().values.get(key); } public static Object setValue(String key, Object value) { return getMyThreadGroup().values.put(key, value); } private static MyThreadGroup getMyThreadGroup() { return (MyThreadGroup) Thread.currentThread().getThreadGroup(); } class MyThreadFactory implements ThreadFactory { public Thread newThread(Runnable r) { return new Thread(MyThreadGroup.this, r, getName()); } } } |
Kommentar hinzufügen