How to use ExecutorService of java concurrent programming?

后端 未结 2 401
陌清茗
陌清茗 2021-01-15 12:07

Iam using below code for uploading images on the remote server.When I use below it is uploading all images cocurrently on remote server.

List

        
2条回答
  •  难免孤独
    2021-01-15 12:33

    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:

    • Use invokeAll() which will simply block until all the tasks submitted complete (see my answer here for more details)
    • Use a CompletionService

    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> uploadTasks = new ArrayList>();
    
    for (final IImage image : Images) { 
       // maybe I got this wrong?  Can't quite parse your code.
       Callable uTask = new uploadImages(image.getDataPath(),image.getDisplayName());
       uploadTasks.add(uTask);
    }
    // this thread will block here until all the tasks complete
    final List> futureList = execService.invokeAll();
    // or you can toss the result entirely if the futures don't matter.    
    

提交回复
热议问题