mardi 26 novembre 2019

What is the cleanest way to cache an instance of ExecutorService when you can't use dependency injection?

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.

Aucun commentaire:

Enregistrer un commentaire