`
clearity
  • 浏览: 35506 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java中的内存泄露

 
阅读更多

Q:在Java中怎么可以产生内存泄露?

A:Java中,造成内存泄露的原因有很多种。典型的例子是一个没有实现hasCode和

equals方法的Key类在HashMap中保存的情况。最后会生成很多重复的对象。所有的内存泄露

最后都会抛出OutOfMemoryError异常,下面通过一段简短的通过无限循环模拟内存泄露

的例子说明一下。

 

 

import java.util.HashMap;
import java.util.Map;
 
public class MemoryLeak {
 
 public static void main(String[] args) {
  Map<Key, String> map = new HashMap<Key, String>(1000);
   
  int counter = 0;
  while (true) {
       // creates duplicate objects due to bad Key class
   map.put(new Key("dummyKey"), "value");
   counter++;
   if (counter % 1000 == 0) {
    System.out.println("map size: " + map.size());
    System.out.println("Free memory after count " + counter
      + " is " + getFreeMemory() + "MB");
       
    sleep(1000);
   }
    
    
  }
 }
 
 // inner class key without hashcode() or equals() -- bad implementation
 static class Key {
  private String key;
 
  public Key(String key) {
   this.key = key;
  }
 
 }
 
 //delay for a given period in milli seconds
 public static void sleep(long sleepFor) {
  try {
   Thread.sleep(sleepFor);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 //get available memory in MB
 public static long getFreeMemory() {
  return Runtime.getRuntime().freeMemory() / (1024 * 1024);
 }
 
}

 

 

结果如下:

 

map size: 1000
Free memory after count 1000 is 4MB
map size: 2000
Free memory after count 2000 is 4MB
map size: 1396000
Free memory after count 1396000 is 2MB
map size: 1397000
Free memory after count 1397000 is 2MB
map size: 1398000
Free memory after count 1398000 is 2MB
map size: 1399000
Free memory after count 1399000 is 1MB
map size: 1400000
Free memory after count 1400000 is 1MB
map size: 1401000
Free memory after count 1401000 is 1MB
.....
.....
map size: 1452000
Free memory after count 1452000 is 0MB
map size: 1453000
Free memory after count 1453000 is 0MB
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at java.util.HashMap.addEntry(HashMap.java:753)
 at java.util.HashMap.put(HashMap.java:385)
 at MemoryLeak.main(MemoryLeak.java:10)

 

Q:怎么解决上面的内存泄露?

A:实现Key类的equals和hasCode方法。

 

   .....
static class Key {
 private String key;
 
 public Key(String key) {
  this.key = key;
 }
 
 
 @Override
 public boolean equals(Object obj) {
 
  if (obj instanceof Key)
   return key.equals(((Key) obj).key);
  else
   return false;
 
 }
 
 @Override
 public int hashCode() {
  return key.hashCode();
 }
}
.....

 

重新执行程序会得到如下结果:

 

map size: 1
Free memory after count 1000 is 4MB
map size: 1
Free memory after count 2000 is 4MB
map size: 1
Free memory after count 3000 is 4MB
map size: 1
Free memory after count 4000 is 4MB
...
Free memory after count 73000 is 4MB
map size: 1
Free memory after count 74000 is 4MB
map size: 1
Free memory after count 75000 is 4MB

 

Q:在实际场景中,你怎么查找内存泄露?

A:通过以下代码获取线程ID

 

C:\>jps
5808 Jps
4568 MemoryLeak
3860 Main

 

通过命令行打开jconsole

 

C:\>jconsole 4568

 

实现了hasCode和equals的Key类和没有实现的图表如下所示:

 

没有内存泄露的:

 



 

造成内存泄露的:

 



 

  • 大小: 68.5 KB
  • 大小: 85 KB
0
0
分享到:
评论
2 楼 clearity 2014-04-26  
793059909 写道
jconsole也是向上趋势,但内存是先减少再增加,一直没有泄漏,大侠看看是那个地方写的有问题:


public static void main(String[] args) {
// TODO Auto-generated method stub

OutofMemoryWithMap test=new OutofMemoryWithMap();
test.createAOutOfMemory();


}

void createAOutOfMemory(){
Map<Key,String> map=new HashMap<Key, String>(1000);
int counter=0;
while (true) {
map.put(this.new Key("dummyKey"), "value");
counter++;
if (counter%1000==0) {
System.out.println("map size:"+map.size());
System.out.println("Free memory after count "+counter+" is "+
getFreeMeory()+" MB");

sleep(1000);
}




}

}


class Key{
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

private String name;
public Key(String name) {
// TODO Auto-generated constructor stub
this.name=name;
}

};


public static void sleep(long sleepFor) {

try {
TimeUnit.MILLISECONDS.sleep(sleepFor);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


public static long getFreeMeory(){

return Runtime.getRuntime().freeMemory()/(1024*1024);

}




map size:3053000
Free memory after count 3053000 is 68 MB
map size:3054000
Free memory after count 3054000 is 68 MB
map size:3055000
Free memory after count 3055000 is 68 MB
map size:3056000
Free memory after count 3056000 is 68 MB
map size:3057000
Free memory after count 3057000 is 68 MB
map size:3058000
Free memory after count 3058000 is 68 MB
map size:3059000
Free memory after count 3059000 is 68 MB
map size:3060000
Free memory after count 3060000 is 68 MB
map size:3061000
Free memory after count 3061000 is 68 MB
map size:3062000
Free memory after count 3062000 is 68 MB
map size:3063000
Free memory after count 3063000 is 68 MB
map size:3064000
Free memory after count 3064000 is 68 MB
map size:3065000
Free memory after count 3065000 is 68 MB
map size:3066000
Free memory after count 3066000 is 67 MB
map size:3067000
Free memory after count 3067000 is 67 MB


将堆设置小些容易看到,只是增加的Entry结构要撑爆你这个大小很难。
1 楼 793059909 2014-04-26  
jconsole也是向上趋势,但内存是先减少再增加,一直没有泄漏,大侠看看是那个地方写的有问题:


public static void main(String[] args) {
// TODO Auto-generated method stub

OutofMemoryWithMap test=new OutofMemoryWithMap();
test.createAOutOfMemory();


}

void createAOutOfMemory(){
Map<Key,String> map=new HashMap<Key, String>(1000);
int counter=0;
while (true) {
map.put(this.new Key("dummyKey"), "value");
counter++;
if (counter%1000==0) {
System.out.println("map size:"+map.size());
System.out.println("Free memory after count "+counter+" is "+
getFreeMeory()+" MB");

sleep(1000);
}




}

}


class Key{
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

private String name;
public Key(String name) {
// TODO Auto-generated constructor stub
this.name=name;
}

};


public static void sleep(long sleepFor) {

try {
TimeUnit.MILLISECONDS.sleep(sleepFor);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


public static long getFreeMeory(){

return Runtime.getRuntime().freeMemory()/(1024*1024);

}




map size:3053000
Free memory after count 3053000 is 68 MB
map size:3054000
Free memory after count 3054000 is 68 MB
map size:3055000
Free memory after count 3055000 is 68 MB
map size:3056000
Free memory after count 3056000 is 68 MB
map size:3057000
Free memory after count 3057000 is 68 MB
map size:3058000
Free memory after count 3058000 is 68 MB
map size:3059000
Free memory after count 3059000 is 68 MB
map size:3060000
Free memory after count 3060000 is 68 MB
map size:3061000
Free memory after count 3061000 is 68 MB
map size:3062000
Free memory after count 3062000 is 68 MB
map size:3063000
Free memory after count 3063000 is 68 MB
map size:3064000
Free memory after count 3064000 is 68 MB
map size:3065000
Free memory after count 3065000 is 68 MB
map size:3066000
Free memory after count 3066000 is 67 MB
map size:3067000
Free memory after count 3067000 is 67 MB

相关推荐

Global site tag (gtag.js) - Google Analytics