2

I'm writing an app the generates a big xlsx file using apache-POI. At a certain time I get OutOfHeapSpace exception.

I want to solve it by writing the content to the xlsx file when I determine that I'll soon be out of space, and thus freeing the memory, and then reading the file from the disk and continuing the writing.

A better solution might be to predefine the number of cells I'll write in each "block" , and then write the block to disk, but in any case this made me wonder if there is a way to determine the heap space that is left at runtime?

AAaa
  • 3,659
  • 7
  • 35
  • 40
  • 2
    Does this help? http://www.exampledepot.com/egs/java.lang/GetHeapSize.html – c24w Jan 22 '12 at 17:56
  • yes it does with the question regarding heap space. bunting solved the greated issue. thanks all. – AAaa Jan 22 '12 at 18:12

4 Answers4

3

The MemoryMXBean can give you a fair amount of information about the current memory usage.

public class PrintMemory {
    public static void main(String[] args) {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        long[] array;
        for (int i = 0; i < 100; i++) {
            array = new long[100000];
            System.out.printf("%d%n", memoryMXBean.getHeapMemoryUsage());
        }
    }
}
Michael Barker
  • 14,153
  • 4
  • 48
  • 55
3

Freeing unused memory at runtime is probably not very reliable since the JVM has considerable freedom in deciding when to garbage collect.

POI recently introduced the SXSSF API that uses streaming and thereby significantly reduces memory footprint for writing spreadsheets. This should help even with very big xsls files. There are a couple of downsides which are shown here. But if you can live with them, this should alleviate you of heap related problems.

Kai Sternad
  • 22,214
  • 7
  • 47
  • 42
2

You can get the available memory, but it only tells you the most you can allocate without triggering a GC.

Instead you can trigger a GC and see how much memory is free after wards. The problem this is it has a perform overhead.

Another option is to monitor the GC cleanups via JMX and see how much is free after it naturally triggers a GC (if it doesn't run, you don't have a problem)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Using one of the coming with the JVM JMX MBeans is worth considering. Like this one MemoryPoolMXBean

Svilen
  • 1,377
  • 1
  • 16
  • 23