메모리 누수 이해 :
엄밀히 말하면 프로그램에서 더 이상 객체를 사용하지 않지만 GC가이를 회수 할 수없는 상황 만 메모리 누수라고합니다.
8 가지 메모리 누수 상황 :
1. 정적 컬렉션 클래스
2. 단일 행 모드
3. 내부 클래스는 외부 클래스를 보유합니다.
4. 데이터베이스 연결, 네트워크 연결 및 io 연결과 같은 다양한 연결
5. 불합리한 변수 범위
6. 해시 값 변경
7. 캐시 누수
**
* 演示内存泄漏
*
* @author shkstart
* @create 14:53
*/
public class MapTest {
static Map wMap = new WeakHashMap();
static Map map = new HashMap();
public static void main(String[] args) {
init();
testWeakHashMap();
testHashMap();
}
public static void init() {
String ref1 = new String("obejct1");
String ref2 = new String("obejct2");
String ref3 = new String("obejct3");
String ref4 = new String("obejct4");
wMap.put(ref1, "cacheObject1");
wMap.put(ref2, "cacheObject2");
map.put(ref3, "cacheObject3");
map.put(ref4, "cacheObject4");
System.out.println("String引用ref1,ref2,ref3,ref4 消失");
}
public static void testWeakHashMap() {
System.out.println("WeakHashMap GC之前");
for (Object o : wMap.entrySet()) {
System.out.println(o);
}
try {
System.gc();
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("WeakHashMap GC之后");
for (Object o : wMap.entrySet()) {
System.out.println(o);
}
}
public static void testHashMap() {
System.out.println("HashMap GC之前");
for (Object o : map.entrySet()) {
System.out.println(o);
}
try {
System.gc();
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("HashMap GC之后");
for (Object o : map.entrySet()) {
System.out.println(o);
}
}
}
/**
* 结果
* String引用ref1,ref2,ref3,ref4 消失
* WeakHashMap GC之前
* obejct2=cacheObject2
* obejct1=cacheObject1
* WeakHashMap GC之后
* HashMap GC之前
* obejct4=cacheObject4
* obejct3=cacheObject3
* Disconnected from the target VM, address: '127.0.0.1:51628', transport: 'socket'
* HashMap GC之后
* obejct4=cacheObject4
* obejct3=cacheObject3
**/