How do I access memory usage programmatically via JMX?

后端 未结 4 1698
[愿得一人]
[愿得一人] 2020-11-29 11:28

I\'m looking for sample Java JMX code to access the values of JMX attributes from another VM.

With JConsole, I have no problem looking at java.lang/Memory/Attributes

4条回答
  •  醉酒成梦
    2020-11-29 11:31

    // Retrieve memory managed bean from management factory.
    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
    MemoryUsage heap = memBean.getHeapMemoryUsage();
    MemoryUsage nonHeap = memBean.getNonHeapMemoryUsage();
    
    // Retrieve the four values stored within MemoryUsage:
    // init: Amount of memory in bytes that the JVM initially requests from the OS.
    // used: Amount of memory used.
    // committed: Amount of memory that is committed for the JVM to use.
    // max: Maximum amount of memory that can be used for memory management.
    System.err.println(String.format("Heap: Init: %d, Used: %d, Committed: %d, Max.: %d",
      heap.getInit(), heap.getUsed(), heap.getCommitted(), heap.getMax()));
    System.err.println(String.format("Non-Heap: Init: %d, Used: %d, Committed: %d, Max.: %d",
      nonHeap.getInit(), nonHeap.getUsed(), nonHeap.getCommitted(), nonHeap.getMax()));
    

提交回复
热议问题