Add executors dynamically based on a condition in java

风格不统一 提交于 2019-12-11 10:44:20

问题


If StrTemp.equals(true), I want code as below (I have 2 threads here):

ExecutorService executor = Executors.newFixedThreadPool(2);

Future<String> f1 = executor.submit(new Callable<String >() {
    public String  call() throws Exception {
        return dao.getS4PricingResponse(pricingRequestTemp);
    }
});
Future<String> f2 = executor.submit(new Callable<String>() {
    public String call() throws Exception {
        return dao.getS4ProductResponse(productRequestTemp);
    }
});

If it's not true I want three threads to be created. I will add one more f3=executor.submit. How can I decide this dynamically and make it more efficient?


回答1:


You are mixing up two things that don't belong together.

  • the executor service and its tasks: that service doesn't know or care about how many threads will be there to run tasks. In other words: just submit your work items into it.
  • but you have to "fix" the number of threads upfront, and the simple solution would look

like this:

int numThreads = (whateverStrTemp.equals(somethingElse)) ? 2 : 3;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
// now submit all the tasks you want to submit ...

Regarding the comment: that one isn't easily possible. The method calls differ in two aspects: the method that gets called and the parameter that gets passed! You could put lambdas for the different calls into a map, but you would probably need another map that holds a lambda that fetches the parameter to pass to the first lambda. From that point of view, I don't see a reasonable way to refactor just this code.

I would step back, and look at the underlying problem you try to solve, and look into ways of designing that differently, to get to a better solution.

Beyond that, you could put all that code into a single loop, and add the futures to a List<Future<String>> instead of creating variables f1, f2, ... (hint: whenever you start using names like foo1, foo2, ... you should stop immediately and use an array or list).



来源:https://stackoverflow.com/questions/54523115/add-executors-dynamically-based-on-a-condition-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!