我有一个文本文件,我需要逐行读取并在每一行上进行一些处理。
ConcurrentMap<String, String> hm = new ConcurrentHashMap<>();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.txt");
InputStreamReader stream = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(stream);
while(true)
{
line = reader.readLine();
if (line == null) {
break;
}
String text = line.substring(0, line.lastIndexOf(",")).trim();
String id = line.substring(line.lastIndexOf(",") + 1).trim();
hm.put(text,id);
}
我需要知道,在 substring()
和 trim()
操作期间创建的字符串何时会被垃圾回收?
另外,字符串 line
怎么样?
最佳答案
一旦超出范围,字符串本身就会被垃圾回收,这发生在 while
循环的每次迭代结束时。但从内存使用的角度来看,这是一个有争议的问题,因为您将此数据存储到映射中,该映射不会超出范围。
如果您提供有关如何使用此 map 的信息,也许可以给出一个解决方案,避免将所有内容存储在内存中。
关于java - 字符串的垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42136265/