3 import java.lang.management.ManagementFactory;
4 import java.lang.management.OperatingSystemMXBean;
6 public class MemorySetting
8 public static final long leaveFreeMinMemory = 536870912; // 0.5 GB
10 public static final long applicationMinMemory = 536870912; // 0.5 GB
12 protected static long getPhysicalMemory()
14 final OperatingSystemMXBean o = ManagementFactory
15 .getOperatingSystemMXBean();
19 if (o instanceof com.sun.management.OperatingSystemMXBean)
21 final com.sun.management.OperatingSystemMXBean osb = (com.sun.management.OperatingSystemMXBean) o;
22 return osb.getTotalPhysicalMemorySize();
24 } catch (NoClassDefFoundError e)
26 // com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
27 System.out.println("No com.sun.management.OperatingSystemMXBean");
30 // We didn't get a com.sun.management.OperatingSystemMXBean.
34 public static long memPercent(int percent)
38 long physicalMem = getPhysicalMemory();
39 if (physicalMem > applicationMinMemory)
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,