Search code examples
javaerror-handlingruntime-errorheap-memory

How do I prevent Java's OutOfMemoryError from occurring on file load?


I am working on a program that loads files and uses their information to populate a Model class. These files can range in size from a few KB to almost a GB. When their sizes fluctuate, so too does the memory used by the Model class.

When I load a file that is large enough, I receive the OutOfMemoryError.

I am able to reject a users request to load a file (based on the file size). How do I examine a file, determine its size, and then determine if the application can handle it?

Is there a way to make this adapt to the amount of RAM on a users' computer?


Solution

  • You can query the JVM to see how much free and used memory there is :
    
    /* Total amount of free memory available to the JVM */
    System.out.println("Free memory (bytes): " + 
    Runtime.getRuntime().freeMemory());
    
    /* This will return Long.MAX_VALUE if there is no preset limit */
    long maxMemory = Runtime.getRuntime().maxMemory();
     /* Maximum amount of memory the JVM will attempt to use */
    System.out.println("Maximum memory (bytes): " + 
    (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
    
    /* Total memory currently in use by the JVM */
    System.out.println("Total memory (bytes): " + 
    Runtime.getRuntime().totalMemory());