How to use ExecutorService of java concurrent programming?

允我心安 提交于 2019-12-01 11:16:38

When you call singleFuture.get() you are waiting for the operation to complete. So the loop won't continue to execute next statement until this one returns a result.

You need to submit your tasks in the first loop and after that, another loop should iterate over the results future.get() on your list to make it async

From @andersoj's answer;

The Pool size should be something related to your CPU cores. Not the number of images you have in hand. Say if you have 2 cored CPU, a coefficient of 5 (just my guess of coefficient) for image uploading io time.

POOL_SIZE = NUM_OF_CPU_CORE*coeffiecient;

andersoj

submit() adds a task to the queue and returns a Future. execute() does not return a Future. See also here. Different orderings you observe may occur as side-effects of the additional management that happens inside submit() and probably are irrelevant. (But see @fmucar's answer...)

Not sure precisely what your question is...

It doesn't really make sense to size your thread pool based on the number of images you want to upload -- probably some small number of threads is sufficient, since you're just trying to keep some TCP streams fed. One thread per image, if the list of images is large, won't buy you anything.

If you are collecting Futures only to know when the uploads complete, consider one of the following:

Edited to add: Good catch, @fmucar, the call to .get() in the logger line forces sequentiality, so the thread pool is a waste.

invokeAll() example

Here's an attempt to give you an invokeAll() example; not sure if it quite matches your code.

final int poolSize = ...;  // see fmucar's answer
final ExecutorService execService = Executors.newFixedThreadPool(poolSize);
final List<Callable<>> uploadTasks = new ArrayList<Callable<>>();

for (final IImage image : Images) { 
   // maybe I got this wrong?  Can't quite parse your code.
   Callable<String> uTask = new uploadImages(image.getDataPath(),image.getDisplayName());
   uploadTasks.add(uTask);
}
// this thread will block here until all the tasks complete
final List<Future<String>> futureList = execService.invokeAll();
// or you can toss the result entirely if the futures don't matter.    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!