[英]leakage of memory in java
http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/#javaexample
代碼中的作者說存在內存泄漏。
public class LeakExample {
static Vector myVector = new Vector();
static HashSet pendingRequests = new HashSet();
public void slowlyLeakingVector(int iter, int count) {
for (int i=0; i<iter; i++) {
for (int n=0; n<count; n++) {
myVector.add(Integer.toString(n+i));
}
for (int n=count-1; n>0; n--) {
// Oops, it should be n>=0
myVector.removeElementAt(n);
}
}
}
這段代碼如何有內存泄漏,而下面沒有。 是什么使兩者不同。
public void noLeak(int size) {
HashSet tmpStore = new HashSet();
for (int i=0; i<size; ++i) {
String leakingUnit = new String("Object: " + i);
tmpStore.add(leakingUnit);
}
// Though highest memory allocation happens in this
// function, but all these objects get garbage
// collected at the end of this method, so no leak.
}
在第一個示例中, 並非所有向量元素都被刪除 (如代碼中的注釋所示)。 由於myVector
是一個static
成員變量 ,只要應用程序正在運行,它就會一直存在,並且每次調用slowlyLeakingVector()
都會隨着時間的推移而增長。
在第二個示例中, tmpStore
是一個局部變量 ,每次從noLeak()
返回后都會進行垃圾回收。
每次運行第一個代碼時,都會添加n個元素,並刪除(n-1)(0處的元素不是),因此向量會緩慢存儲永遠不會使用的元素。 並且由於向量是靜態的,它將一直存在,直到JVM關閉,泄漏內存。
在第二個示例中,tmpStore可以在每次調用結束時進行垃圾回收,因此不會泄漏。
這里的關鍵是
for (int n=count-1; n>0; n--) {
// Oops, it should be n>=0
myVector.removeElementAt(n);
}
最后一個元素永遠不會被刪除,因為n
在循環中從不為0
,即removeElementAt(0)
永遠不會運行。 這導致元素在向量中緩慢累積。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.