Skip to content Skip to sidebar Skip to footer

Set Null To Thread To Prevent Memory Leak In Ondestroy Android

I am using Thread for some Async operations. Now primarily I have 3 Threads like : private lateinit var horse1Thread: Thread private lateinit var horse2Thread: Thread private latei

Solution 1:

Setting them to null does nothing because the threads are still running and the virtual machine will keep track of them while they do.

What you need to do is introduce a way to signal that the thread should no longer continue. This is usually done by checking the Thread.isInterrupted() in the loop and ending the loop if it is true. Then you only need to call Thread.interrupt() inside your onDestroy method to clean up the threads.

Solution 2:

I don't think that you should care about setting these fields to null. Thread should finish his work and after that Thread will be in TERMINATED state. And later Garbage collector will clean it without you. You should care only about state of these threads, and build logic inside these threads in such way, that they finish theirs work without any endless looping.

So basically you need some trigger in you long operation inside thread, and by click on button this trigger should skip(or cancel) your long operation inside thread. And after that thread will go to TERMINATED thread by himself.

Solution 3:

Actually, there's even a description on Thread.stop() why it shouldn't be used:

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#stop()

This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running.

Post a Comment for "Set Null To Thread To Prevent Memory Leak In Ondestroy Android"