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?
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.
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.