user3870075
user3870075

Reputation: 141

How can I read a large file and free the memory at the end?

I have a ".txt" file with the size of 6.29mb and 11234 line.
I tried reading that file in java.

Using this code:

File file = new File(path);
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while( (line=br.readLine()) != null ){

}
br.close();
fis.close();

That way it's fast,
but the problem is when it runs it takes about ~700mb in memory
and when the BufferedReader is closed my java program still takes ~700mb
I don't understand why?

What is the solution to clear the memory?

Please help.

Thanks.

Upvotes: 0

Views: 913

Answers (2)

Hosseini
Hosseini

Reputation: 557

it's obvious you can't but you can

  • you can assign null to object you wanna free it from GC

enter image description here

  • you can use WeakReferences :

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:

WeakReference weakWidget = new WeakReference(widget); and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately .

HashMap<StringBuilder, Integer> map = new HashMap<>();
WeakReference<HashMap<StringBuilder, Integer>> aMap = new WeakReference<>(map);

map = null;

while (null != aMap.get()) {
    aMap.get().put(new StringBuilder("abbas"),
            new Integer(123));
    System.out.println("Size of aMap " + aMap.get().size());
    System.gc();
}
System.out.println("Its garbage collected");

//Size of aMap 1
//Its garbage collected

and in a general way you create Object with new but you have no power to free it or run the GC .

Upvotes: 1

markbernard
markbernard

Reputation: 1420

The JVM does not necessarily release memory back to the OS after it has asked for it. It expands quickly to meet your needs, up to the maximum allowed. Once it has the memory it tends to hold onto it for a long time. Even though your program is now only using maybe 50MB, the JVM will still hold onto the other 650MB.

Upvotes: 2

Related Questions