KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > util > MemoryUtils


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

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 JavaDoc 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 JavaDoc rt = Runtime.getRuntime();
23         long mem = rt.freeMemory();
24         return (int) (mem >> 10);
25     }
26     
27     private static synchronized void collectGarbage() {
28         Runtime JavaDoc 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