) String and Memory leakage in Java

Source: Internet
Author: User
Http://clarkht.iteye.com/blog/482644

String oldstr = "Hello, Clark ";

String newstr = oldstr. substring (0, 4 );

In fact, for oldstr, It is a char [] array [h, E, l, l, 0, C, L, A, R, K], for the substring operation, newstr does not copy the char [] array of oldstr by itself. Hello creates a new char [] array, but Java implements string reusing optimization behind it, instead of creating a new char array, it reuses the original char array. So there won't be many fragments of the original char [] array. Reference columns on http://www.javablogging.com/string-and-memory-leaks:

Java code

Public static void sendemail (string emailurl ){

String email = emailurl. substring (7); // 'mailto: 'prefix has 7 letters

String username = Email. substring (0, email. indexof ("@"));

String domainname = Email. substring (email. indexof ("@"));

}

 

Public static void main (string [] ARGs ){

Sendemail ("mailto: user_name@domain_name.com ");

}

However, this is generally good, but it also has a price. According to explain collected, because newstr still has reference to the char [] array of oldstr. This can easily cause an outof Memory exception. The solution is to enable newstr to own its char [] array, that is, force itself to create its char [] array during substring, in this way, there will be no garbage collected problems (reachable but unused !) What to do:

Java code

String sub = new string (oldstring. substring (0, 4 ));

---------------------------------------------------------------

To avoid Memory copying and speed up, Sun JDK directly reuses the char [] of the original string object, and uses the offset and length to identify different string content. That is to say, the small String object produced by substring still points to the char [] of the large string object. The same is true for split. This explains why the char [] of the string object in hashmap is so big.

-------------------------------------------------------

Refer:

Http://jarfield.iteye.com/blog/583946

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.