georgij
georgij

Reputation: 2200

Memory leaks with HashMap/HashSet on Android

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?

Upvotes: 0

Views: 1033

Answers (3)

androidworkz
androidworkz

Reputation: 2942

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

Upvotes: 0

Robin
Robin

Reputation: 24262

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500515

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?

Upvotes: 0

Related Questions