简体   繁体   English

Android上的HashMap / HashSet导致内存泄漏

[英]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). 我有一个Android应用程序,在其中我使用HashMap,在其中我将每个执行任务(可运行)的线程(值)保留在其中。 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). 问题在于它们似乎在完成并从HashMap中删除后似乎从未被GC释放(并且没有从其他任何地方引用它们)。 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. 尝试改为使用HashSet,但结果相同。

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? 为什么GC不喜欢收集它们?

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. 即使您在HashMap中删除了对线程的引用,如果它实际上尚未完成,也不会被GC。 The run method must complete for that to occur. 运行方法必须完成才能发生。

How certain are you that you're actually removing them from the HashMap or HashSet ? 您如何确定实际上要从HashMapHashSet删除它们? What's the size() of the collection when you create your dump? 创建转储时集合的size()是多少?

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. 只要您不将hasmap或hashset声明为弱引用,GC就不会对其进行任何操作,因为您的应用程序对它具有强引用。 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 http://download-llnw.oracle.com/javase/1.4.2/docs/api/java/lang/ref/WeakReference.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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