[英]How to manage memory when using ExecutorService?
我需要使用multithreading
執行大量任務。
我使用ExecutorService
提交大量Callable objects
,每個Callable object
包含一些執行所需的resource
。
問題
這些任務太多,以至於提交給ExecutorService
的Callable objects
占用了太多內存,因此heap
耗盡。
我想知道, JVM
何時釋放這些Callable objects
的空間?
在完成任務后它是否立即執行此操作,如何管理用於ExecutorService
的內存?
我想控制提交到ExecutorService
,例如,當內存不足時阻止提交util完成一些任務和空閑空間。 可以嗎?
整個代碼太復雜,我將附加我的代碼的主框架。
public class MyCallable implements Callable<Result> {
... // Some members
public MyCallable(...) {
...
}
@Override
public Result call() throws Exception {
... // Doing the task
}
}
class MyFutureTask extends FutureTask<Result> {
... // Some members
public MyFutureTask(...) {
super(new MyCallable(...));
}
@Override
public void done() {
Result result = get();
... // Something to do immediately after the task is done
}
}
// Here is the code to add tasks
ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
while (...) {
... // Reading some data from files
executor.submit(new MatchFutureTask(...));
}
executor.shutdown();
如果您正在使用ExecutorService,則必須將BlockingQueue傳遞給構造函數,對吧? 我假設您正在使用ThreadPoolExecutor。 使用具有固定容量的ArrayBlockingQueue,並將ThreadPoolExecutor.CallerRunsPolicy傳遞給ThreadPoolExecutor構造函數。 如果將maximumPoolSize設置為某個合理的值,這將相當有效地限制您的提交率。
為了回答您的第一個問題,VM將“在”之后的某個時間釋放內存,不再有任何對象的引用。 如果Callable在狀態方面是自包含的,一旦完成執行,VM應該在給出內存不足錯誤之前對其進行垃圾收集。
方法Runtime.getRuntime().freeMemory()
將告訴你JVM有多少可用內存。 您可以編寫一個ThreadFactory
實現,在創建新線程之前檢查此值。
似乎使用Executors.newCachedThreadPool()減少了30%的內存 - 60%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.