Unit of Work - Pattern

Inhaltsverzeichnis
Zuletzt aktualisiert
by Anonym (13 Aug)
Re: XPath of Node (Software Development)

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.

  1. Create a ThreadGroupLocal. This holds a value/values for each ThreadGroup shared between threads in that group.
  2. Create a custom ThreadGroup which holds a thread safe Map of values.

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.
This structure is used to run a large number of unrelated tasks at once. (Although the single threaded portions have to wait for each other)

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());
        }
    }
}

Stichwörter:

Geben Sie Stichwörter ein, die dieser Seite hinzugefügt werden sollen:
Wait Image 
Sie suchen ein Stichwort? Beginnen Sie einfach zu schreiben.