How to fix Android memory leak associated with Threads?

So, I found that with MAT I create several Threads with each surfaceCreate

I think I need these threads, but this method calls multiple instances of ViewThread as the user is viewing my application, which is a memory leak.

How can I reorganize the way I create and process my threads so that this does not happen, or how can I stop the leak?

 @Override public void surfaceCreated(SurfaceHolder holder) { loading=false; if (!mThread.isAlive()){ mThread = new ViewThread(this); mThread.setMenuRunning(true); mThread.start(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (mThread.isAlive()){ mThread.setMenuRunning(false); } } 

I opened and sailed off my game’s Career action five times, and this is what appears on MAT

leak

EDIT: Since then, I have found that depending on the surfaceDestroyed to destroy my threads is unreliable. Now I call the corresponding thread-killing calls from another method, launched by onPause .

+8
android memory-leaks
source share
3 answers

You should use the WeakReference to link to the Career in your topic. Thus, the link will be cleared if there are no more links to the Career.

You can track all links in MAT by right-clicking on a career and selecting Path To GC Roots, then with all links. This will show you the path to the object stored in memory. Make sure you either clear these links when you're done with the activity, or use WeakReferences to clear the GC automatically.

+4
source share

Inside surfaceDestroyed you need to wait to make sure the thread is stopped before you return.

You can turn to this question for more details.

 @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; mThread.setRunning(false); while (retry) { try { mThread.join(); retry = false; } catch (InterruptedException e) { } } } 
+1
source share

So I fixed it by commenting on one line:

 @Override public void surfaceCreated(SurfaceHolder holder) { loading=false; if (!mThread.isAlive()){ //mThread = new ViewThread(this); mThread.setMenuRunning(true); mThread.start(); } } 

This was also combined with WeakReference and SurfaceDestroyed . I will check it later and determine if it will be possible to delete only one line or a combination of this and a weak link or other thing, and then give the answer

+1
source share

All Articles