我遇到了关于内存泄漏的这篇文章,.It说,下面的代码有记忆泄漏.But,我不明白它是如何泄漏内存的。
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.Random;
public class MemoryLeak
{
// Generates long lines of gibberish words.
static class GibberishGenerator implements Iterator<String>
{
private int MAX_WORD_LENGTH = 20;
private int WORDS_PER_LINE = 250000;
private String alphabet = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
public boolean hasNext() {
return true;
}
public String next() {
StringBuffer result = new StringBuffer();
for (int i = 0; i < WORDS_PER_LINE; i++) {
if (i > 0) { result.append(" "); }
result.append(generateWord(MAX_WORD_LENGTH));
}
return result.toString();
}
public void remove() {
// not implemented
}
private String generateWord(int maxLength) {
int length = (int)(Math.random() * (maxLength - 1)) + 1;
StringBuffer result = new StringBuffer(length);
Random r = new Random();
for (int i = 0; i < length; i++) {
result.append(alphabet.charAt(r.nextInt(alphabet.length())));
}
return result.toString();
}
}
// A "good" word has as many vowels as consonants and is more than two
// letters long.
private static String vowels = "aeiouAEIOU";
private static boolean isGoodWord(String word) {
int vowelCount = 0;
int consonantCount = 0;
for (int i = 0; i < word.length(); i++) {
if (vowels.indexOf(word.charAt(i)) >= 0) {
vowelCount++;
} else {
consonantCount++;
}
}
return (vowelCount > 2 && vowelCount == consonantCount);
}
public static void main(String[] args) {
GibberishGenerator g = new GibberishGenerator();
List<String> goodWords = new ArrayList<String>();
for (int i = 0; i < 1000; i++) {
String line = g.next();
for (String word : line.split(" ")) {
if (isGoodWord(word)) {
goodWords.add(word);
System.out.println("Found a good word: " + word);
break;
}
}
}
}
}完整的文章请参考以下链接:
这里有什么可能的泄漏?StringBuffer是用来生成吉布伯西什世界的。
发布于 2014-12-19 19:13:36
您应该继续阅读,这是添加到goodWords列表中的引用,如题为Spoiler的一节中讨论的那样
罪魁祸首是: String line = g.next();for (String word : line.split(“")) { if (isGoodWord(word)) { goodWords.add(word);
并进一步发展
更新:从Java1.7UPDATE 6开始,字符串行为发生了变化,因此使用子字符串不会保留原来的字节数组。这对我设计的例子来说是个小小的打击,但寻找问题的整体方法仍然有效。
https://stackoverflow.com/questions/27572324
复制相似问题