Friday, August 12, 2022

Menelusuri Pemakaian Memory di Java

 Terkadang kita curiga apakah ada baris di program yang memakan memory dan tidak pernah terbebaskan oleh tukang sampah (garbage collector) ?


Mungkin bisa pakai freeMemory dari java.lang.Runtime


int repeated = 300000;//Integer.MAX_VALUE;

StringBuilder sb = new StringBuilder();

Runtime runtime = Runtime.getRuntime();

sb.append("init Memory \n Used memory: ");

long currentMemory = runtime.totalMemory() - runtime.freeMemory();

long lastFreeMemory = currentMemory;

sb.append( currentMemory );

sb.append("\t memory being used (implied): ");

sb.append( currentMemory - lastFreeMemory );


sb.append("\nrepeated log\n Used memory: ");

for(int i = 0; i < repeated; i++) {

// lakukan sesuatu yang memakan memory

}

currentMemory = runtime.totalMemory() - runtime.freeMemory();

sb.append( currentMemory );

sb.append("\t memory being used (implied): ");

sb.append( currentMemory - lastFreeMemory );

lastFreeMemory = currentMemory;

sb.append("\nCall Garbage Collector:\n Used memory: ");

System.gc();

try { Thread.sleep(1000); }

catch(InterruptedException e) { 

; // terlalu malas 

}


Selamat mencoba.

0 comments: