http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/#javaexamplejava中的內存泄露
整個代碼中的作者說有內存泄漏。
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.
}
感謝您的幫助 – John 2010-10-19 10:17:29