java中内存溢出和内存泄漏的区别

虽然在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);
}

原文地址:https://www.cnblogs.com/omery/p/8057994.html