1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.monitoring;
35
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.inject.Singleton;
40
41
42
43
44 @Singleton
45 public class SystemMonitor {
46
47 public static final String MEMORY_LIMIT_IS_REACHED_STRING_FORMAT = "Your server is currently low on memory. %s. Please try again later or contact your administrator if this happens frequently.";
48
49 public static final String MEMORY_VALUES_STRING_FORMAT = "Memory values: max = {}mb, total = {}mb, free = {}mb -> remaining = {}mb / thresholds = {}mb or {}%";
50
51 public static final long BYTE_TO_MEGABYTE_FACTOR = 1024 * 1024;
52
53 public static final int MEMORY_THRESHOLD_PERCENTAGE = 10;
54
55 public static final int MEMORY_THRESHOLD_IN_MB = 50;
56
57 private final static Logger log = LoggerFactory.getLogger(SystemMonitor.class);
58
59
60
61
62
63
64 public boolean isMemoryLimitReached() {
65 Runtime runtime = Runtime.getRuntime();
66 return isBelowAllThresholds(runtime.maxMemory() / BYTE_TO_MEGABYTE_FACTOR, runtime.totalMemory() / BYTE_TO_MEGABYTE_FACTOR, runtime.freeMemory() / BYTE_TO_MEGABYTE_FACTOR);
67 }
68
69
70
71
72
73
74
75 protected boolean isBelowAllThresholds(final long maxMemoryInMb, final long totalMemoryInMb, final long freeMemoryInMb) {
76
77 final long remainingInMB = freeMemoryInMb + (maxMemoryInMb - totalMemoryInMb);
78 final boolean isLowerThanThresholdInMB = remainingInMB < MEMORY_THRESHOLD_IN_MB;
79 final boolean isLowerThanThresholdPercentage = (100 * remainingInMB / maxMemoryInMb) < MEMORY_THRESHOLD_PERCENTAGE;
80 final boolean isMemoryLimitReached = isLowerThanThresholdInMB && isLowerThanThresholdPercentage;
81
82 log.debug(MEMORY_VALUES_STRING_FORMAT, maxMemoryInMb, totalMemoryInMb, freeMemoryInMb, remainingInMB, MEMORY_THRESHOLD_IN_MB, MEMORY_THRESHOLD_PERCENTAGE);
83
84 if (isMemoryLimitReached) {
85 log.warn(MEMORY_VALUES_STRING_FORMAT, maxMemoryInMb, totalMemoryInMb, freeMemoryInMb, remainingInMB, MEMORY_THRESHOLD_IN_MB, MEMORY_THRESHOLD_PERCENTAGE);
86 }
87
88 return isMemoryLimitReached;
89 }
90 }