How do I find the physical memory size in Java?

前端 未结 7 886
心在旅途
心在旅途 2021-01-07 22:02

I\'m writing an installer that will tune the configuration of the product for the particular hardware on which it will be run. In particular, I want to determine how much p

7条回答
  •  暖寄归人
    2021-01-07 22:43

    import java.lang.management.ManagementFactory;
    
    import javax.management.AttributeNotFoundException;
    import javax.management.InstanceNotFoundException;
    import javax.management.MBeanException;
    import javax.management.MBeanServer;
    import javax.management.MalformedObjectNameException;
    import javax.management.ObjectName;
    import javax.management.ReflectionException;
    
    public class Main {
      public static void main(String[] args) throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException  {
      /* Total number of processors or cores available to the JVM */
    
    
          MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
          Object attribute = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "TotalPhysicalMemorySize");
          Object attribute2 = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "FreePhysicalMemorySize");
          System.out.println("Total memory: "+ Long.parseLong(attribute.toString()) / 1024  +"MB");
          System.out.println("Free  memory: "+ Long.parseLong(attribute2.toString()) / 1024  +"MB");    
    
     }
    }
    

提交回复
热议问题