Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Leak Java OutOfMemoryError in Vector List

I am running a multithreaded application with 3 threads:

  • Main Thread - Vector List to store Objects
  • AdderThread - Add Objects to this Vector List
  • RemoverThread - Remove Objects with vectorList.clear() method (synchronized)

Application runs fine but after few hours it gives OutOfMemoryError.

I generated Heap dump and analysed with eclipse MAT which shows vectorList class taking all the memory.

Does clear method free memory which was occupied by individual objects ?

How to fix this?


1 Answers

If you are adding tasks faster than you are freeing them, you will get an OutOfMemoryError as your Vector will grow to the limit of your memory.

Instead of using a Vector for a work queue, I suggest using a BlockingQueue from the concurrency libraries.

e.g.

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.

In fact it would be much simpler to use an ExecutorService as this combines a work queue with a thread pool. You submit tasks to the executor and it processes them. This avoids the need to write any code for the RemoverThread as such.

like image 145
Peter Lawrey Avatar answered Jun 23 '26 18:06

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!