Tuesday, September 01, 2009

Design, Don't do it

Are you designing a thread-safe front to a single-threaded resource? Relax.

The wrong way

Write layers and layers of complexly interacting abstraction over an object pool, letting the object pool (hopefully) protect you from threading concerns.

The right way

Use the JDK:

public class FooService {
    private final UnsafeResource resource;
    private final ExecutorService service;

    public FooService(final UnsafeResource resource) {
        this.resource = resource;
        service = createPoolFor(resource);
    }

    public <T, E extends Exception> Future<T> submit(
            final Work<T, E> work) {
        return service.submit(new Callable<T>() {
            T call() throws E {
                return work.use(resource);
            }
        });
    }

    public interface Work<T, E extends Exception> {
        T use(final UnsafeResource resource) throws E;
    }

    // Good place for an extension point depending on your needs
    private static ExecutorService createPoolFor(final UnsafeResource resource) {
        return newSingleThreadExecutor(new ThreadFactory() {
            public Thread newThread(final Runnable r) {
                return new Thread(r,
                        FooService.class.getSimpleName() + ": " + resource);
            }
        });
    }
}
Post a Comment