Java String.substring method potential memory leak?

前端 未结 3 1454
灰色年华
灰色年华 2020-11-29 07:49

I was going through the String class API and looks like there is a potential memory leak caused by substring method as it shares same character array as original String.

3条回答
  •  無奈伤痛
    2020-11-29 08:28

    1. It was the case until Java 7u6 - you would generally deal with the issue by doing:

      String sub = new String(s.substring(...)); // create a new string
      

      That effectively removes the dependency and the original string is now available for GC. This is by the way one of the only scenarios where using the string constructor makes sense.

    2. Since Java 7u6, a new String is created and there is no memory issue any longer.

提交回复
热议问题