will the below code will cause memory leak? Assume the method is in Activity
public void main(){
final Object obj = new Object();
Runnable run = new Runnable() {
@Override
public void run() {
Thread.sleep(25000);//sleep
obj.hashCode();//do something
}
};
new Thread(run).start();
}
Does this lead to leak? Since the thread refer the Object which is created outside it
Thanks Ram
Yes, threads don't follow the Activity lifecycle, so if you create a thread and the Runnable is an anonymous class it will have an implicit reference to the Activity because java will create an inner class.
If the Activity orientation changes or any other type of configuration changes Android will destroy the Activity and create a new one, however, it can't be deallocated by the garbage collector because threads are considered GC roots, the net effect is that you will have 2 activities in memory until your thread ends. If your thread ends before a configuration change you're ok, but this is not recommended practice since you usually can't guarantee that.
A solution would be to declare the runnable as an inner static class or an external class, and when a configuration change happens any reference to the activity that you have in the Thread/Runnable you pass the reference of the new activity.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments