[英]How to stop blocking queue size from increasing in thread pool executor service?
[英]Executor Thread Pool - limit queue size and dequeue oldest
我正在為 spring 引導應用程序中生成的消息的消費者使用固定線程池。 我的生產者生產(很多)快於生產者能夠處理消息的速度,因此線程池的隊列似乎正在“泛濫”。
限制隊列大小的最佳方法是什么? 預期的隊列行為是“如果隊列已滿,則移除頭部並插入新的 Runnable”。 是否可以像這樣配置 Executors 線程池?
ThreadPoolExecutor
通過ThreadPoolExecutor.DiscardOldestPolicy
支持此功能:
被拒絕任務的處理程序,丟棄最早的未處理請求,然后重試執行,除非執行程序關閉,在這種情況下,任務將被丟棄。
您需要使用此策略進行mannully構建池,例如:
int poolSize = ...;
int queueSize = ...;
RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardOldestPolicy();
ExecutorService executorService = new ThreadPoolExecutor(poolSize, poolSize,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(queueSize),
handler);
這將為您傳遞的大小創建一個線程池。
ExecutorService service = Executors.newFixedThreadPool(THREAD_SIZE);
這在內部創建了一個ThreadPoolExecutor實例,它實現了ExecutorService。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
要創建自定義thead池,您可以這樣做。
ExecutorService service = new ThreadPoolExecutor(5, 5,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(10));
在這里,我們可以使用LinkedBlockingQueue的重載構造函數指定隊列的大小。
public LinkedBlockingQueue(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node<E>(null);
}
希望這可以幫助。 干杯!!!
例如,如果您使用一次能夠連接 100 個連接的數據庫 (psql)。 任務可能需要 2000 毫秒...
int THREADS = 50;
ExecutorService exe = new ThreadPoolExecutor(THREADS,
50,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10),
new ThreadPoolExecutor.CallerRunsPolicy()); ```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.