01: package Schmortopf.Main;
02:
03: /**
04: * Singleton
05: *
06: * It is used by various Schmortopf classes for memory management.
07: *
08: * Its task is to call the GC with some intelligence.
09: * If the app memory is low, there is no need to call the GC.
10: * Also it prevents fast supsequent calls of the GC - one call
11: * per second is enough, because the GC call itself needs some
12: * time too and many calls to it only consume time and maybe memory.
13: */
14:
15: public class GCMemoryChecker {
16:
17: private static GCMemoryChecker ThisChecker = null;
18:
19: private long lastGCCallTime = 0; // used by checkMemory()
20:
21: private GCMemoryChecker() {
22: } // Constructor
23:
24: /**
25: * GC management
26: */
27: public void checkMemory(boolean intensively, boolean actEarly) {
28: if (actEarly) {
29: this .checkEarly(intensively);
30: } else {
31: this .checkNormal(intensively);
32: }
33: }
34:
35: private void checkEarly(boolean intensively) {
36: // We don't act more frequently than once all 0.5 seconds :
37: long this Time = System.currentTimeMillis();
38: if (this Time - this .lastGCCallTime > 500) {
39: this .lastGCCallTime = this Time;
40: long jvmMemory = Runtime.getRuntime().totalMemory();
41: long freeMemory = Runtime.getRuntime().freeMemory();
42: if ((freeMemory * 10) < (jvmMemory * 5)) // call the gc, if we are below 50 percent freememory
43: {
44: System.gc();
45: System.gc();
46: } // if
47: if (intensively) // one more time in any case
48: {
49: System.gc();
50: System.gc();
51: }
52: } // if
53: } // checkMemory
54:
55: private void checkNormal(boolean intensively) {
56: // We don't act more frequently than once all 3 seconds :
57: long this Time = System.currentTimeMillis();
58: if (this Time - this .lastGCCallTime > 3000) {
59: this .lastGCCallTime = this Time;
60: long jvmMemory = Runtime.getRuntime().totalMemory();
61: long freeMemory = Runtime.getRuntime().freeMemory();
62: if ((freeMemory * 10) < (jvmMemory * 4)) // call the gc, if we are below 40 percent
63: {
64: System.gc();
65: System.gc();
66: } // if
67: if (intensively) // one more time in any case
68: {
69: System.gc();
70: System.gc();
71: }
72: } // if
73: } // checkMemory
74:
75: public static GCMemoryChecker getInstance() {
76: if (ThisChecker == null) {
77: ThisChecker = new GCMemoryChecker();
78: }
79: return ThisChecker;
80: } // getInstance
81:
82: } // GCMemoryChecker
|