简体   繁体   中英

Can setting Looper in a thread cause a java memory leak?

Lets say I have a thread defined like so:

public class MyThread extends Thread {

    Looper someLooper;

    public void setLooper(Looper looper){
      someLooper= looper;
    }

    @Override
    public void run() {
        System.out.println("MyThread - START "+Thread.currentThread().getName());
  System.out.println("mylooper:"+someLooper.toString());

        }
    }
}

Now, let's say in the mainThread activity screen i do this:

MyThread t = new MyThread();
t.setLooper(Looper.getMainLooper());
t.start();

Will this be a memory leak since the Looper is being referenced forever in the child thread ? Will the GC be able to collect the memory from the mainThread activity or does it have to wait until the looper is freed? I think that it won't be a memory leak as the looper is associated with a thread, not a activity context. I need confirmation.

The main thread never ends as long as your app is running, so no it won't leak any memory. There's no reference to Activity in Looper- at least not directly (messages added to the Looper may have references to the Activity, but that's a different matter, and is only really a problem if they have a very long delay).

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