1 5 package org.h2.util; 6 7 public class MemoryUtils { 8 9 private static long lastGC; 10 private static int GC_DELAY = 50; 11 private static int MAX_GC = 8; 12 13 public static int getMemoryUsed() { 14 collectGarbage(); 15 Runtime rt = Runtime.getRuntime(); 16 long mem = rt.totalMemory() - rt.freeMemory(); 17 return (int) (mem >> 10); 18 } 19 20 public static int getMemoryFree() { 21 collectGarbage(); 22 Runtime rt = Runtime.getRuntime(); 23 long mem = rt.freeMemory(); 24 return (int) (mem >> 10); 25 } 26 27 private static synchronized void collectGarbage() { 28 Runtime runtime = Runtime.getRuntime(); 29 long total = runtime.totalMemory(); 30 long time = System.currentTimeMillis(); 31 if (lastGC + GC_DELAY < time) { 32 for (int i = 0; i < MAX_GC; i++) { 33 runtime.gc(); 34 long now = runtime.totalMemory(); 35 if (now == total) { 36 lastGC = System.currentTimeMillis(); 37 break; 38 } 39 total = now; 40 } 41 } 42 } 43 44 } 45 | Popular Tags |