简体   繁体   中英

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 lateinit var timerThread: Thread

Calling stop() in onDestroy() of activity causes a UnsupportedOperationException and I thought of setting these values to null to allow GC collection and prevent memory leak. Since my fields are non-null types I cant set them to null . So is this my only option? Or does kotlin provide a way to free the memory held by these fields? I can set their type to nullable but I feel it defeats the purpose?

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.

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.

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.

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