Skip to content
Advertisement

How to manage Heap Space in Java

I’m trying to recursively traverse through my Drive to search some files. The code is working fine when there are limited folders/files but when I target my search to C drive where in I have lots of files it throws Out of Heap memory.

Exception in thread “Thread-4” java.lang.OutOfMemoryError: Java heap space

  1. Please suggest me some good memory management tricks especially when we do recursive calls.
  2. Or give me better approach to traverse through directories without recursion.

and I don’t want to increase the maximum allowable heap space as it is just like postponing the issue for time being.

Code:

void iterateDirectory(String somedir) {


        File dir = new File(somedir);
        File[] files = dir.listFiles();
        if (files != null) {
            for (int id = 0; id < files.length; id++) {
                if (files[id].isDirectory() == false) 
                {
                   fsTree.add(files[id].toString()); // taking list of files
                } 
                else 
                {
                    iterateFilesInDirectory(files[id].getAbsolutePath());
                }
            }
        }
    }

Advertisement

Answer

There are limitations as to what recursion can do, namely with respect to stack/heap usage. Remember that whatever you can do recursively, you can do iteratively; rewrite your code to use an iterative solution instead.

Alternate solution: There is an interface in java.nio that can be used to recursively walk down a filesystem’s structure. Take a look at this trail, and SimpleFileVisitor.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement