Thread objects not garbage collected after being finished

后端 未结 4 1808
遥遥无期
遥遥无期 2021-02-08 13:28

I noticed that my application is leaking memory. This can be seen in DDMS, and I managed to get a OutOfMemoryError.

I found the source of the leak. One of the activitie

4条回答
  •  野的像风
    2021-02-08 14:11

    The anonymous runnable class used by the thread would have a reference to the activity ('this'). As the thread is referenced by the activity, and the runnable in the thread references the activity, the GC will never collect either of them.

    Try doing something more like this:

    private static RunnableClass implements Runnable
    {
        @Override
        public void run() {
            while (!finished) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Log.d(getClass().getName(), "Thread finished");
        }
    });
    
    Thread thread = new Thread(new RunnableClass());
    

提交回复
热议问题