Created
February 29, 2016 07:21
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.