01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.util;
07:
08: /**
09: * This is a utility class with functions to measure the free and used memory.
10: */
11: public class MemoryUtils {
12:
13: private static long lastGC;
14: private static final int GC_DELAY = 50;
15: private static final int MAX_GC = 8;
16:
17: /**
18: * Get the used memory in KB.
19: *
20: * @return the used memory
21: */
22: public static int getMemoryUsed() {
23: collectGarbage();
24: Runtime rt = Runtime.getRuntime();
25: long mem = rt.totalMemory() - rt.freeMemory();
26: return (int) (mem >> 10);
27: }
28:
29: /**
30: * Get the free memory in KB.
31: *
32: * @return the used memory
33: */
34: public static int getMemoryFree() {
35: collectGarbage();
36: Runtime rt = Runtime.getRuntime();
37: long mem = rt.freeMemory();
38: return (int) (mem >> 10);
39: }
40:
41: private static synchronized void collectGarbage() {
42: Runtime runtime = Runtime.getRuntime();
43: long total = runtime.totalMemory();
44: long time = System.currentTimeMillis();
45: if (lastGC + GC_DELAY < time) {
46: for (int i = 0; i < MAX_GC; i++) {
47: runtime.gc();
48: long now = runtime.totalMemory();
49: if (now == total) {
50: lastGC = System.currentTimeMillis();
51: break;
52: }
53: total = now;
54: }
55: }
56: }
57:
58: }
|