1. Memory leak caused by singleton. , Due to the static characteristics of the singleton, its life cycle is the same as the life cycle of the application. Therefore, if an object is no longer needed, if the singleton object has a reference to the object, the object cannot be recycled normally, and the memory leakage.
Solution: The life cycle of a single instance is as long as the application to prevent memory leaks.
// 使用了单例模式 public class AppManager { private static AppManager instance; private Context context; private AppManager(Context context) { this.context = context; } public static AppManager getInstance(Context context) { if (instance != null) { instance = new AppManager(context); } return instance; } }
2. Memory leak when the container is used. Memory leak refers to the execution of the following code unrelated to the vector after the vector operation is completed. If a GC operation occurs, this A series of objects cannot be recycled, and the memory leak here may be short-lived, because those objects can still be recycled after the entire method() method is executed.
The solution is very simple, just manually assign the value to null:
void method(){ Vector vector = new Vector(); for (int i = 1; i<100; i++) { Object object = new Object(); vector.add(object); object = null; } //...对v的操作 vector = null; //...与v无关的其他操作 }
The above is the detailed content of Solutions to Java memory leaks. For more information, please follow other related articles on the PHP Chinese website!