Your code ... as written ... reads lines and accumulates them in a StringBuilder
. The mere fact that you are accumulating the lines is a form of memory leak.
The best way to prevent that leak is to change your application to work like this:
BufferedReader reader = new BufferedReader(new FileReader(vCache));
String line = null;
while ((line = reader.readLine()) != null) {
process(line);
}
In other words, DON'T accumulate the lines in memory. Process them as you read them and then discard them.
If your processing is such that you have to accumulate the lines in memory, then you will get better memory usage if you allocate the StringBuilder
like this:
StringBuilder sb = new StringBuilder(fileSizeInCharacters);
That will avoid the need to reallocate, which can (in the worst case) require 3 times as many characters as the file size (in characters).
However you will run into the same problem, sooner or later. Accumulating the file content in memory doesn't scale.
Your comments indicate that this is really a JSON processing problem. Here's a Q&A on the topic of streaming JSON processing:
The idea of a streaming API is that you don't need to convert the JSON "object" into an in-memory tree structure that represents the whole thing.