JAL-3477 New jvmmemmax config option in getdown and getdown config. Set to 32G cap.
[jalview.git] / getdown / src / getdown / core / src / main / java / jalview / bin / MemoryPercent.java
diff --git a/getdown/src/getdown/core/src/main/java/jalview/bin/MemoryPercent.java b/getdown/src/getdown/core/src/main/java/jalview/bin/MemoryPercent.java
new file mode 100644 (file)
index 0000000..2de2157
--- /dev/null
@@ -0,0 +1,53 @@
+package jalview.bin;
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.OperatingSystemMXBean;
+
+public class MemoryPercent
+{
+
+  protected static long getPhysicalMemory()
+  {
+    final OperatingSystemMXBean o = ManagementFactory
+            .getOperatingSystemMXBean();
+
+    try
+    {
+      if (o instanceof com.sun.management.OperatingSystemMXBean)
+      {
+        final com.sun.management.OperatingSystemMXBean osb = (com.sun.management.OperatingSystemMXBean) o;
+        return osb.getTotalPhysicalMemorySize();
+      }
+    } catch (NoClassDefFoundError e)
+    {
+      // com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
+      System.out.println("No com.sun.management.OperatingSystemMXBean");
+    }
+
+    // We didn't get a com.sun.management.OperatingSystemMXBean.
+    return -1;
+  }
+
+  public static long memPercent(int percent)
+  {
+    return memPercent(percent);
+  }
+  public static long memPercent(float percent)
+  {
+    long memPercent = -1;
+
+    long physicalMem = getPhysicalMemory();
+    if (physicalMem > MemorySetting.applicationMinMemory)
+    {
+      // try and set at least applicationMinMemory and thereafter ensure
+      // leaveFreeMinMemory is left for the OS
+      memPercent = Math.max(MemorySetting.applicationMinMemory,
+              (long) (physicalMem
+                      - Math.max(physicalMem * (100 - percent) / 100,
+                              MemorySetting.leaveFreeMinMemory)));
+    }
+
+    return memPercent;
+  }
+
+}