当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Reuse a callable instance seems to work. Is this ok though?

问题描述:

My program is an infinite loop. Before entering the loop I instantiate 2 callables. They each perform an HTTP request that need to be run in parallel and return a result. They are different java classes and they do not share any attribute / data. Yet, They both update their own internal attributes, some sort of counters that I need to keep alive from the start of the program, until I stop it.

My code looks like this. Please forgive me if it's horrific, I haven't been coding for 6 years.

callable1 = new Callable1();

callable2 = new Callable2();

while(true) {

//Preparation of the dynamic parameters

...

callable1.setData(some_dynamic_parameters1);

callable2.setData(some_dynamic_parameters2);

ExecutorService threadPool = Executors.newFixedThreadPool(2);

CompletionService<String> completion = new ExecutorCompletionService<String>(threadPool);

completion.submit(callable1);

completion.submit(callable2);

threadPool.shutdown();

//I need to wait for both tasks to complete before going further

String firstReply = completion.take().get();

String secondReply = completion.take().get();

...

}

The code for both callables looks like this. They differ in their call() method details.

public class callable1 extends Callable {

private counters = new PositionCounters();

private data = null;

public void setData(data) {

this.data = data;

}

public String call() {

//Create HTTP query from information contained in [data]

...

//update internal counter.

counters.update(query_result)

}

}

Each time, I submit the callables to the executor, the "counters" in each are updated, and it seems to do the job in parallel. But I am not convinced that my solution is the best one because I read that a thread can never be reused. Yet, that's what I do here. I would like your expert opinion on this. What do you think is the best way to achieve this ?

THanks for your help !

网友答案:

A callable is not a thread, it is just a wrapper for the code that will be executed by the thread. You can reuse it, as long as its state hasn't got stale or you can reset it (or it is modified so that the next run will just need that state etc...). Still you should determine if this really solves any performance issue, as this seems to be 2 object constructions per call (+GC).

分享给朋友:
您可能感兴趣的文章:
随机阅读: