Skip to content

Instantly share code, notes, and snippets.

@asafm
Created February 29, 2016 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asafm/47d60b2ca4860c74027a to your computer and use it in GitHub Desktop.
Save asafm/47d60b2ca4860c74027a to your computer and use it in GitHub Desktop.
Show resident memory behavior after releasing memory in two flavors: direct and heap
package io.logz.netty;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class MemoryMain {
public static void main(String[] args) {
System.out.println("hello there - process id "+getCurrentProcessId());
List<ByteBuffer> arrays = new ArrayList<>();
new Thread(() -> {
for (int i = 0; i < 1000*4; i++) {
ByteBuffer bb = ByteBuffer.allocateDirect(1000*1000);
// ByteBuffer bb = ByteBuffer.allocate(1000*1000);
for (int j = 0; j < bb.capacity(); j++) {
bb.put((byte) ('a' + (j % 20)));
}
arrays.add(bb);
}
System.out.println("Heap: "+getHeapUsage() +"mb");
System.out.println("Total Memory: "+Runtime.getRuntime().totalMemory() / (1024*1024)+"mb");
System.out.println("Done allocating buffers. Waiting 10 seconds");
if (waitAbit(10)) return;
arrays.clear();
System.gc();
System.out.println("Cleared buffers. Waiting 10 seconds");
if (waitAbit(10)) return;
System.out.println("Heap: "+getHeapUsage() +"mb");
System.out.println("Total Memory: "+Runtime.getRuntime().totalMemory() / (1024*1024)+"mb");
System.out.println("Just waiting anothe 20sec");
if (waitAbit(20)) return;
}).start();
if (waitAbit(180)) return;
}
private static boolean waitAbit(int seconds) {
try {
Thread.sleep(1000*seconds);
} catch (InterruptedException e) {
System.out.printf("Interrupted!");
return true;
}
return false;
}
public static int getCurrentProcessId() {
return Integer.valueOf(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
}
public static long getHeapUsage() {
return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / (1024*1024);
}
}
@asafm
Copy link
Author

asafm commented Feb 29, 2016

After GC, if allocate() used, resident is still high although heap is at 40mb. When using allocateDirect() resident is back to 40mb after GC. So JVM is reluctant to give back free memory to the operating system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment