Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

Talk about memory leaks and overflows in Android.

Although I have been studying Android for more than a year since college, I should not be very familiar with the underlying knowledge and some concepts in Android. I plan to familiarize myself with them during this long holiday.

Android Memory Leak#

Memory leak refers to the situation where variable references that can no longer be accessed are saved, causing the garbage collector to be unable to reclaim memory.
In other words:
In Java, the lifecycle of some objects is limited. When they have completed specific logic, they will be reclaimed. However, if an object is still referenced by other objects when it should have been reclaimed in its lifecycle, it will cause a memory leak.
Specific example:

public class LeakAct extends Activity {  
    @Override
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_leak);
        test();
    } 
    
    public void test() {    
        new Thread(new Runnable() {      
            @Override
            public void run() {        
                while (true) {          
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }z
            }
        }).start();
    }
}

test is a non-static inner class. When we finish, this instance will not be destroyed, and the GC mechanism will not perform garbage collection on this instance because anonymous inner classes and non-static inner classes hold strong references to the outer class. In other words, test holds a strong reference to the outer activity, and the while(true) loop inside the thread is an infinite loop, so the thread will not stop, and the strong reference to the outer activity will not disappear. This causes a memory leak.

Solution

  1. Convert the inner class to a static inner class;
  2. If there is a strong reference to a property in the Activity, change the reference to a weak reference;
  3. When the Activity executes onDestroy, end these time-consuming tasks if the business allows.

Android Memory Overflow#

Memory overflow refers to the situation where an app requests memory from the system that exceeds the maximum threshold, and the system will not allocate additional space, resulting in memory overflow.

  • A typical example is loading multiple large images, which consumes a lot of memory. You can compress the quality or size of the images appropriately.
  • When a certain interface has a memory leak and you repeatedly enter this interface, new objects will continue to be created but cannot be reclaimed, eventually leading to memory exhaustion and memory overflow.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.