tags:

views:

64

answers:

3

I have an Android application where I use HashMap where I keep my Threads (values) each executing a task (Runnable). To identify the Threads I use Strings as keys. The Threads are alive as long as they execute a task what is usually not very long. The problem is that they seem to never been released by GC after finishing and being removed from the HashMap (and they are not referenced from anywhere else). If I create a dump of my application there are as many of my tasks in memory as started through the life of the application. Have tried to use HashSet instead but with the same result.

In code I start them with this few lines:

Thread image_fetch_thread = new Thread(new ImageFetchTask(image_url, this));

this.running_image_fetch_threads.put(image_url, image_fetch_thread);

image_fetch_thread.start();

and at some point later they become removed:

this.running_image_fetch_threads.remove(image_url);

Why GC don't like to collect them?

A: 

How certain are you that you're actually removing them from the HashMap or HashSet? What's the size() of the collection when you create your dump?

Jon Skeet
I used remove(key) to remove the Threads by key and even made sure to call GC every time size() dropped to 0. So I think the removal works at least.
georgij
+1  A: 

Are you certain that your threads are actually finishing? Even if you remove the reference to your Thread in the HashMap, it will not be GCed if it has not actually finished. The run method must complete for that to occur.

Robin
Yes, they finish for sure (they are quite simple, no loops). They have not finished at the time they are removed from the collection because the removal is triggered from the Thread itself as the last action before finish. Could this be a problem?
georgij
No, as long as they are removed from the map they should be eligible for collection once the thread is finished. Can you post some sample code?
Robin
A: 

As long as you don't declare the hasmap or hashset as weakreference the GC can't do anything to it because your application has a strong reference to it. My answer is in additon to what Robin already said.

http://download-llnw.oracle.com/javase/1.4.2/docs/api/java/lang/ref/WeakReference.html

androidworkz