问题
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?
回答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.
回答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.
回答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.
来源:https://stackoverflow.com/questions/51880051/set-null-to-thread-to-prevent-memory-leak-in-ondestroy-android