Search code examples
javaqueuethreadpoolexecutorservice

Multi-producer single-consumer executor service design


I have a java.util.BlockingQueue which is full of POJOs which need to be serviced by an ExecutorService. This queue must be serviced by a single thread, but will be pushed to from multiple threads at once.

In the past, I've written my solution to look a bit like this, but I really despise it:

executorService.execute(new Runnable() {

    @Override
    public void run() {
        while (true) {
            try {
                POJO job = blockingQueue.take();
                servicePOJO(job);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
});

Is there a better way of writing this, or is this the optimal way of doing it? The reason I don't like doing it is because if I need to add multiple consumers, I need to run the above in a loop with the size of the actual thread pool.


Solution

  • I would use the ExecutorService with a task per object.

    public <POJO> void asyncServicePOJO(final POJO pojo) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                servicePOJO(pojo);
            }
        });
    }
    

    There is no need for an extra queue.