Differences in memory overflow and memory leaks in Java

Source: Internet
Author: User

Although in Java we do not care about the release of memory, the garbage collection mechanism helps us to reclaim unwanted objects, but in fact improper operations can also produce memory problems: memory overflow, memory leaks

Memory overflow: Out of memory: a simple, easy-to-read understanding is that it is not enough.

Memory leaks: Leak of Memory: an object allocates RAM and is not released in time at the end of use, resulting in memory being consumed, not cleaned up in time, and the actual available memory is reduced, as if memory leaks.

For example, improper use of the substring () method in Jdk6 is prone to memory leaks, JDK7 does not have to consider

JDK6 substring Source: Uses the same char array as the parent string 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 Source: You can see that the last creation of a new char array

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);
}

Differences in memory overflow and memory leaks in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.