Which ThreadPool in Java should I use?

前端 未结 5 1731
花落未央
花落未央 2021-02-06 06:00

There are a huge amount of tasks. Each task is belong to a single group. The requirement is each group of tasks should executed serially just like executed in a single thread an

5条回答
  •  隐瞒了意图╮
    2021-02-06 06:44

    A simple approach would be to "concatenate" all group tasks into one super task, thus making the sub-tasks run serially. But this will probably cause delay in other groups that will not start unless some other group completely finishes and makes some space in the thread pool.

    As an alternative, consider chaining a group's tasks. The following code illustrates it:

    public class MultiSerialExecutor {
        private final ExecutorService executor;
    
        public MultiSerialExecutor(int maxNumThreads) {
            executor = Executors.newFixedThreadPool(maxNumThreads);
        }
    
        public void addTaskSequence(List tasks) {
            executor.execute(new TaskChain(tasks));
        }
    
        private void shutdown() {
            executor.shutdown();
        }
    
        private class TaskChain implements Runnable {
            private List seq;
            private int ind;
    
            public TaskChain(List seq) {
                this.seq = seq;
            }
    
            @Override
            public void run() {
                seq.get(ind++).run(); //NOTE: No special error handling
                if (ind < seq.size())
                    executor.execute(this);
            }       
        }
    

    The advantage is that no extra resource (thread/queue) is being used, and that the granularity of tasks is better than the one in the naive approach. The disadvantage is that all group's tasks should be known in advance.

    --edit--

    To make this solution generic and complete, you may want to decide on error handling (i.e whether a chain continues even if an error occures), and also it would be a good idea to implement ExecutorService, and delegate all calls to the underlying executor.

提交回复
热议问题