简体   繁体   中英

Android Memory Leak new Thread()

It's about android application memory leak of Thread object.

I didn't know yet following code cause memory leak since I started android program for 3 years.

Thread t = new Thread();

t is NOT detected by garbage collector.

Question is how can i release local variable t from vm memory?

I decide to experiment

I made button on my app which is conduct following code.

for(int i=0;i<1000;i++)
{
   Thread t = new Thread();
}

I expected local variable t will be deallocated some day.

And I executed it with debug mode and opened E-clipse DDMS perspective.

I choose my application thread on my android device(2.3.6) and clicked "update heap" button

so I can check heap size and allocated on real time.

It started with total heap size 5.445MB and allocated 2.779 MB.

And I clicked button which is produce 1000 thread objects.

It changed by heap size 5.508MB and allocated 3.058 MB.

As you know there is "Cause GC" button on DDMS perspective.

I clicked that button. But Allocated memory was still 3.058MB.

I clicked my button again to produce another 1000 thread objects.

And I clicked hopeless "Gause GC" button.

Eventually heap size was gone about 20MB and out of memory exception caused.

How can I release Thread instance object?

After you're done using the thread, call interupt() .

And I don't know if it's necessary, but it might be a good idea to set t=null as was suggested by Johannes.

But after you've stopped the thread, then it is up to the JVM's Garbage Collector to handle the destruction of the thread itself.

I do not have an android device to test it on, but I would think that a Thread needs to die before it can be garbage collected in addition to not being referenced by any variable.

Try starting the threads in your loop like this:

for(int i=0;i<1000;i++)
{
    Thread t = new Thread();
    t.start();
    t = null;
}

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