[英]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.