2 java memory multithreading memory-leaks vector
我正在运行一个包含3个线程的多线程应用程序:
应用程序运行正常但几个小时后就会出现OutOfMemoryError.
我生成了Heap转储并使用eclipse MAT进行分析,它显示了vectorList类占用了所有内存.
clear方法是否释放了由单个对象占用的内存?
如何解决这个问题?
如果你以比释放它们更快的速度添加任务,你将得到一个OutOfMemoryError,因为你的Vector会增长到你的记忆极限.
我建议使用并发库中的BlockingQueue,而不是使用Vector作为工作队列.
例如
BlockingQueue<Work> queue = new ArrayBlockingQueue<>(MAX_TASKS_WAITING);
AdderThread calls queue.put(work); // blocks if the queue is full
RemoverThread call queue.take(); // blocks if there is nothing to do.
Run Code Online (Sandbox Code Playgroud)
事实上,使用ExecutorService会更简单,因为它将工作队列与线程池相结合.您将任务提交给执行程序并处理它们.这样就不需要为RemoverThread编写任何代码了.