简体   繁体   English

字符串垃圾回收

[英]Garbage Collection for Strings

I have a text file which I need to read line by line and do some processing on each line. 我有一个文本文件,需要逐行读取并在每一行上进行一些处理。

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);
}

I need to know, when will the strings created during the substring() and trim() operations be garbage collected? 我需要知道,什么时候会在substring()trim()操作期间创建的substring()被垃圾收集? Also, what about the String line ? 另外,字符串line呢?

The strings themselves will be garbage collected as soon as they go out of scope, which happens at the end of each iteration of the while loop. 一旦超出范围,字符串本身将被垃圾回收,这在while循环的每次迭代结束时发生。 But from a memory usage point of view this is a moot point because you are storing this data into a map which will not go out of scope. 但是从内存使用的角度来看,这是有争议的,因为您要将这些数据存储到不会超出范围的映射中。

If you include information about how you are using this map, maybe a solution can be given which avoids having to store everything in memory. 如果您包含有关如何使用此地图的信息,则可以提供一种避免将所有内容存储在内存中的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM