ThreadPoolExecutor Block When Queue Is Full?

前端 未结 8 1835
无人及你
无人及你 2020-11-29 17:42

I am trying to execute lots of tasks using a ThreadPoolExecutor. Below is a hypothetical example:

def workQueue = new ArrayBlockingQueue(3, f         


        
8条回答
  •  感动是毒
    2020-11-29 18:24

    What you need to do is to wrap your ThreadPoolExecutor into Executor which explicitly limits amount of concurrently executed operations inside it:

     private static class BlockingExecutor implements Executor {
    
        final Semaphore semaphore;
        final Executor delegate;
    
        private BlockingExecutor(final int concurrentTasksLimit, final Executor delegate) {
            semaphore = new Semaphore(concurrentTasksLimit);
            this.delegate = delegate;
        }
    
        @Override
        public void execute(final Runnable command) {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
    
            final Runnable wrapped = () -> {
                try {
                    command.run();
                } finally {
                    semaphore.release();
                }
            };
    
            delegate.execute(wrapped);
    
        }
    }
    

    You can adjust concurrentTasksLimit to the threadPoolSize + queueSize of your delegate executor and it will pretty much solve your problem

提交回复
热议问题