0

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.

Elydasian
  • 2,016
  • 5
  • 23
  • 41
user3870075
  • 141
  • 1
  • 3
  • 10
  • Its hard to believe that reading ~7MB file causes JVM to allocate ~700MB. Maybe you have some code inside your while loop, like string concatanation? – marcinj Jun 14 '16 at 19:32
  • If you are doing `String` concatanation, you may be better off using `StringBuilder` since `String` is immutable – Orin Jun 14 '16 at 19:35

2 Answers2

2

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.

markbernard
  • 1,412
  • 9
  • 18
1

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 .

Hosseini
  • 547
  • 3
  • 15