rkabhishek
rkabhishek

Reputation: 926

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? Also, what about the String line?

Upvotes: 0

Views: 110

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

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. 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.

Upvotes: 3

Related Questions