90257d1a442c14e5c3d73babf09d6f1867a28fc3
[jalview.git] / getdown / src / getdown / core / src / main / java / jalview / bin / MemoryPercent.java
1 package jalview.bin;
2
3 import java.lang.management.ManagementFactory;
4 import java.lang.management.OperatingSystemMXBean;
5
6 public class MemoryPercent
7 {
8
9   protected static long getPhysicalMemory()
10   {
11     final OperatingSystemMXBean o = ManagementFactory
12             .getOperatingSystemMXBean();
13
14     try
15     {
16       if (o instanceof com.sun.management.OperatingSystemMXBean)
17       {
18         final com.sun.management.OperatingSystemMXBean osb = (com.sun.management.OperatingSystemMXBean) o;
19         return osb.getTotalPhysicalMemorySize();
20       }
21     } catch (NoClassDefFoundError e)
22     {
23       // com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
24       System.err.println(
25               "No com.sun.management.OperatingSystemMXBean: cannot get total physical memory size");
26     }
27
28     // We didn't get a com.sun.management.OperatingSystemMXBean.
29     return -1;
30   }
31
32   public static long memPercentAmount(int percent)
33   {
34     return memPercentAmount((float)percent);
35   }
36   public static long memPercentAmount(float percent)
37   {
38     long memPercentAmount = -1;
39
40     long physicalMem = getPhysicalMemory();
41     if (physicalMem > MemorySetting.applicationMinMemory)
42     {
43       // try and set at least applicationMinMemory and thereafter ensure
44       // leaveFreeMinMemory is left for the OS
45
46       memPercentAmount = (long) ((physicalMem * percent) / 100F);
47
48       // check for memory left for OS
49       if (physicalMem - memPercentAmount < MemorySetting.leaveFreeMinMemory)
50       {
51         memPercentAmount = physicalMem - MemorySetting.leaveFreeMinMemory;
52       }
53
54       // check for minimum application memsize
55       if (memPercentAmount < MemorySetting.applicationMinMemory)
56       {
57         memPercentAmount = MemorySetting.applicationMinMemory;
58       }
59     } else {
60       // not enough memory for application, just try and grab what we can!
61       memPercentAmount = physicalMem;
62     }
63
64     return memPercentAmount;
65   }
66
67 }