简体   繁体   中英

RandomAccessFile Memory Leak

I am using RandomAccessFile in java. I have a memory leak problem. I have simplified my code to the following:

public static void main(String[] args) throws IOException, InterruptedException
{
    RandomAccessFile r = new RandomAccessFile(new File("test.dat"), "rw");
    r.write(new byte[150000000], 0, 150000000);
    r.getFD().sync();
    r.close();
    r = null;

    while (true) { Thread.sleep(1000); }
}

After executing this code (and allowing sufficient time for GC) the reported memory usage for the application is a little over 150MB.

What have I missed? Or is Java to blame?

The GC will only make the memory available for use within the JVM. Memory freed by GC is not automatically returned to the OS. The JVM is generally very reluctant in returning memory to the OS, since it may need it again soon, and getting memory from the OS is a relatively expensive operation.

To see the percentages of heap memory in use and free, you can use Visual VM . If you want the JVM to return memory to the OS mor eagerly, you can use the tuning parameters of the Oracle JVM , specifically -XX:MaxHeapFreeRatio and -XX:MinHeapFreeRatio

How do you check the memory usage? The usage reported by the OS only indicates that the java heap has expanded in size. You can't know wether the heap is empty, or whether it is full but with objects that are eligible for GC.

You should use some java related tool (eg VisualVM, or jmap). This will give you a better indication of the heap memory status. With VisualVM you can activate a GC manually, and then check the heap occupancy to determine whether there is a memory leak or not.

Memory is only reclaimed when the GC is run, and the GC only runs when it needs to. Try calling System.gc() if you want to see the memory usage go down.

BTW: Java isn't guarenteed to return the memory to the OS, rather it tends to increases the free memory internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM