问题
I have looked through all the memory leak solutions for java substring method. I still get the out of memory error due to this issue. I have an arraylist of string which are of length 1000-3500. i index them and store them. The issue is each string needs to be run through loop to store all possible varying lengths of same string. To do this, i use for loop and substring method. and this method causes the memory leak problem.
A sudo code of what i have done:
for(int i=0;i<str.length;i++)
{
//create substring and index it
str.substring(0,(str.length()-i));
}
str: string. and this above loops runs till all the string within the arraylist are indexed. I tried to fix the leak by,
1.
for(int i=0;i<str.length;i++)
{
//create substring and index it
new String(str.substring(0,(str.length()-i)));
}
2.
for(int i=0;i<str.length;i++)
{
//create substring and index it
new String(str.substring(0,(str.length()-i)).intern());
}
3.
for(int i=0;i<str.length;i++)
{
//create substring and index it
new String(str.substring(0,(str.length()-i))).intern();
}
Still i have the issue. My java version is: 1.7.0_17.
Edit:
I understand this is not a memory leak problem from the comments. I am indexing some continuous strings. Say for example,
String s= abcdefghijkl;
i want index each string as :
abcdefghjk
abcdefghj
abcdefhg
abcdefh
abcdef
abcde
abcd
..
..
a
To perform this,i get a string,then perform substring operation,get that string and index them.
回答1:
There is no leak.
Please note that you're creating a huge amount of String objects. If a String has a length of 1000 characters you're creating 1000 objects.
Is it really needed to create so many String objects? Would it be possible for example to use a char[] to achive what you want?
回答2:
There are 2 things:
First: ".intern()" keeps the string in an internal cache that is usually not garbage collected - please don't use it if you're not 100% sure why you are using it.
Second: there is a constructor from String taking char[] like this:
final char[] chars = str.toCharArray ();
for(int i=0;i<chars.length;i++)
{
//create substring and index it
new String(chars, 0, chars.length-i);
}
-> this is also more efficient (in terms of speed)
回答3:
This problem fixed in the JDK 1.7 by returning the new copy of character array.
public String(char value[], int offset, int count) {
//check boundary
// It return new copy on array.
this.value = Arrays.copyOfRange(value, offset, offset + count);
}
public String substring(int beginIndex, int endIndex) {
//check boundary
int subLen = endIndex - beginIndex;
return new String(value, beginIndex, subLen);
}
http://javaexplorer03.blogspot.in/2015/10/how-substring-memory-leak-fixed-in-jdk.html?q=itself+implements+Runnable
来源:https://stackoverflow.com/questions/17359047/memory-leak-issue-on-using-java-substring-method