简体   繁体   中英

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?

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM