Reject policy of bounded queue in Java

When using executorservice, we know that there is a queue in executorservice to save the submitted tasks. Through different constructors, we can create unbounded queues (executorservice. Newcachedthreadpool) and bounded queues (executorservice newfixedthreadpool (int nthreads)).

Unbounded queue is well understood. We can submit tasks to executorservice without restrictions. So for bounded queues, what should I do if the queue is full?

Today, we will introduce the reject policy of executorservice in Java.

Taking ThreadPoolExecutor, the concrete implementation of executorservice, as an example, it defines four saturation policies. They are abortpolicy, discardpolicy, discardoldestpolicy and callerrunspolicy.

If you want to set the saturation policy in ThreadPoolExecutor, you can call the setrejectedexecutionhandler method, as shown below:

        ThreadPoolExecutor threadPoolExecutor= new ThreadPoolExecutor(5, 10, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(20));
        threadPoolExecutor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.AbortPolicy()
        );

In the above example, we define a thread pool with an initial 5 and a maximum of 10 worker threads, and define that the capacity of the queue is 20. If the submitted task exceeds the capacity, the abortpolicy policy policy is used.

AbortPolicy

DiscardPolicy

DiscardOldestPolicy

CallerRunsPolicy

Using semaphore

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>