JAL-3278 A system.out.println turned into a cache.log.error
[jalview.git] / src / jalview / bin / MemorySetting.java
1 package jalview.bin;
2
3 import java.lang.management.ManagementFactory;
4 import java.lang.management.OperatingSystemMXBean;
5
6 public class MemorySetting
7 {
8   public static final long leaveFreeMinMemory = 536870912; // 0.5 GB
9
10   public static final long applicationMinMemory = 536870912; // 0.5 GB
11
12   protected static long getPhysicalMemory()
13   {
14     final OperatingSystemMXBean o = ManagementFactory
15             .getOperatingSystemMXBean();
16
17     try
18     {
19       if (o instanceof com.sun.management.OperatingSystemMXBean)
20       {
21         final com.sun.management.OperatingSystemMXBean osb = (com.sun.management.OperatingSystemMXBean) o;
22         return osb.getTotalPhysicalMemorySize();
23       }
24     } catch (NoClassDefFoundError e)
25     {
26       // com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
27       Cache.log.error("No com.sun.management.OperatingSystemMXBean");
28     }
29
30     // We didn't get a com.sun.management.OperatingSystemMXBean.
31     return -1;
32   }
33
34   public static long memPercent(int percent)
35   {
36     long memPercent = -1;
37
38     long physicalMem = getPhysicalMemory();
39     if (physicalMem > applicationMinMemory)
40     {
41       // try and set at least applicationMinMemory and thereafter ensure
42       // leaveFreeMinMemory is left for the OS
43       memPercent = Math.max(applicationMinMemory,
44               physicalMem - Math.max(physicalMem * (100 - percent) / 100,
45                       leaveFreeMinMemory));
46     }
47
48     return memPercent;
49   }
50
51 }