1. 程式人生 > >java中內存溢出和內存泄漏的區別

java中內存溢出和內存泄漏的區別

int end fbo gin 一個 urn 垃圾 substring 內存問題 內存溢出

雖然在java中我們不用關心內存的釋放, 垃圾回收機制幫助我們回收不需要的對象,但實際上不正當的操作也會產生內存問題:如,內存溢出、內存泄漏

內存溢出:out of memory:簡單通俗理解就是內存不夠用了 。

內存泄漏:leak of memory:一個對象分配內存之後,在使用結束時未及時釋放,導致一直占用內存,沒有及時清理,使實際可用內存減少,就好像內存泄漏了一樣。

比如在jdk6中不恰當使用substring()方法容易引發內存泄漏,JDK7 就無需考慮

jdk6的substring源碼:使用的是和父字符串同一個char數組value

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);

jdk7的substring源碼:可以看出最後創建了一個新的char數組

public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}

java中內存溢出和內存泄漏的區別