将NULL设置为Thread以防止onDestroy Android中的内存泄漏 [英] Set null to Thread to prevent memory leak in onDestroy Android
问题描述
我正在使用Thread进行一些异步操作.现在主要是我有3个线程,如:
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
在活动onDestroy()
中调用stop()
会导致UnsupportedOperationException
,我想到将这些值设置为null
以允许GC收集并防止内存泄漏.由于我的字段是non-null
类型,因此无法将它们设置为null
.那么这是我唯一的选择吗?还是kotlin提供了一种释放这些字段所拥有的内存的方法?我可以将它们的类型设置为可为空,但是我觉得它没有达到目的?
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?
推荐答案
将它们设置为null
不会执行任何操作,因为线程仍在运行,并且虚拟机将在运行时跟踪它们.
Setting them to null
does nothing because the threads are still running and the virtual machine will keep track of them while they do.
您需要做的是引入一种信号通知该线程不再继续的方法.通常,通过在循环中检查Thread.isInterrupted()
并在循环为true时结束循环来完成此操作.然后,您只需要在onDestroy
方法内调用Thread.interrupt()
即可清理线程.
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.
这篇关于将NULL设置为Thread以防止onDestroy Android中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!