Android memory leaks

Basic knowledge of JAVA memory leaks

1. JAVA memory allocation strategy

2. How does JAVA manage memory

3. Memory leaks in JAVA

Let's first look at the strategy of JAVA memory allocation

In JAVA memory allocation, it is divided into three parts

1. static storage area

It mainly stores static data, global quantities, and so on. It has been allocated when the program is compiled, and it exists all the time during the entire program operation.

2. Stack storage area

The basic type variables created in the method body will create memory space on the stack. Create objects.

3. heap storage

The heap area is also known as dynamic memory allocation. Usually it is the memory from our new object. When the memory is not in use, it will be reclaimed by the garbage collection period.

The difference between the stack area and the heap area:

Stack area: It is the basic type of variable created in the method body. and object reference variables. When an object is created in the method body, java will allocate memory space for the variable in the stack area. When the scope of the object is exceeded, the object will be invalid. The memory space occupied by this object will also be used by other methods. The biggest difference is that the variable space in the heap will be managed by java's garbage collection period. The generated object array, etc. can also define a special variable in the stack area. And this variable is the memory address where the object is stored.

How does JAVA manage memory

It's a matter of allocation and release

Memory Leaks in JAVA

A memory leak means that useless objects (objects that are no longer used) continue to occupy memory or the memory of useless objects cannot be released in time. As a result, the waste of memory space becomes a memory leak.

The accumulation of memory leaks can cause OOM. Serious memory consequences.

1. Simple interest, such as simple interest holding a non-application context

2. Anonymous inner class

In JAVA, non-static inner classes will hold references to outer classes by default

3.handler

To change the handler to static. Then use weak references to hold the external context

Or rmovecallbackmessage in detroy.

4. Avoid using static variables

Background processes that occupy a large amount of memory will be recycled first.

5. Memory leak caused by resource bit closing

Such as broadcast receiver, contentresever, document, cursor, strame, socket, bitmap, etc.

6. Memory leak caused by asyntask

You can asyntask.cancel in destroy

Guess you like

Origin blog.csdn.net/howlaa/article/details/128813962