WestCoastProjects
WestCoastProjects

Reputation: 63231

Do the thread pools created by Executors ever release their memory?

Consider the basic fixed thread pool:

Executors.newFixedThreadPool(MaxListeners)

It is my intention to continually submit new tasks - in response to incoming tcp socket service requests.

However it seems that when the Runnable code within each task were completed - that the memory they consume were not released? I am seeing continuously growing jvm memory usage.

The application tends to process a set of tasks in groups. We can see a stairstep memory usage pattern: after each set of tasks the memory is a couple of tens of megabytes higher. Waiting even tens of minutes (to hours) does not result in memory being reclaimed.

So two questions:

Upvotes: 2

Views: 2297

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

ThreadPoolExecutor does all necessary cleaning automatically after each task execution. But it only cleans its own memory. Objects created during task execution is responsibility of the programer. If memory grows after tasks executions it means there are references to obects that tasks created or to tasks themselves somewhere in your program.

Upvotes: 0

Jose Martinez
Jose Martinez

Reputation: 12022

Objects in Java do not get garbage collected until there are no references left to those objects. Do not look at this as a thread issue but as an object reference issue. That is to say, find out what living objects are still referencing that data.

Luckily there are tools to help you with this. You can use profilers to inspect what objects are still alive and you can even get data about those objects. Attached is an example of the default profiler in the Netbeans IDE. It is profiling my application and displaying all living Timeline objects (thats' what I focused in on). But it could have easily shown me all objects. This is a quick way of seeing which objects are causing memory leaks or just staying alive too long.

enter image description here

EDIT: Please note, @JBNIzet pointed out.

Objects can be GCed even if there are still references to them. What matters is if there is a chain of strong references to the object from a GC root (thread stack or static variable).

This is very important to note, as most things will never get cleaned up if all references to that object needed to be gone.

Upvotes: 1

Related Questions