0

I'm currently working on a task where whenever a new HTTP request is made to the server, an instance of the handler is created. This handler will hold the logic of processing the HTTP request. This background information is needed to note that a new instance of the handler will be created for each request. I cannot change that since that is just how the architecture was built.

Now, I have a scenario where I would like use an ExecutorService (say newFixedThreadPool) in the logic of this handler. Since a new instance of the handler is created every time, I cannot do the following within the handler class:

private static final ExecutorService MY_EXECUTOR = ExecutorService.newFixedThreadPool(5);

This would be pointless since that line would be executed for every single request.

My initial solution was to have another class which would hold a reference to the ExecutorService, and then I would inject this instance into the handler. Unfortunately, I cannot inject arbitrary classes into the handler (once again, due to the architecture).

With these constraints in mind, how can I have a reusable ExecutorService?
This was the only thing I could come up with:

public final class HandlerHelper {

    private static final ExecutorService MY_EXECUTOR = ExecutorService.newFixedThreadPool(5);

    private HandlerHelper() { }

    public ExecutorService getExecutorService () { return MY_EXECUTOR; }
}

However, that's pretty ugly. So I'm hoping somebody can help me out with a better design here.

Now that I think about it, I could do this:

class Handler {

    private static final ExecutorService MY_EXECUTOR;

    static {
        MY_EXECUTOR = ExecutorService.newFixedThreadPool(5);
    }
}

Not sure which approach is better (if any of them are even good).

gjvatsalya
  • 1,129
  • 13
  • 29
  • Now that I think about it, I could do this ? Yes you can. ExecutorService is thread safe to use static keyword. More detailed discussion https://stackoverflow.com/questions/45009918/threadsafe-static-initialization-of-executorservice – wahyu eko hadi saputro Nov 27 '19 at 02:30
  • The very first line is how I manage a specific resource pool with minimum effort tbh. – Rogue Nov 27 '19 at 13:17

0 Answers0