Like and see, unlimited power. Wechat search “program ape Alang”.

This article Github.com/niumoo/Java… And unread code sites have been included, there are many knowledge points and a series of articles.

This article introduces the concepts and usage of Java JMX technology.

This article is part of the Java performance analysis and optimization series. Click to view all articles.

Series of links: www.wdbyte.com/java/perfor…

  1. Arthas – Java’s ultimate tool for online problem location processing
  2. Java benchmarking using JMH
  3. Overview of monitoring and management in Java
  4. Monitor and manage Java programs using JMX

What is JMX?

Java Management Extensions (JMX) technology is a standard feature of the Java SE platform. It provides a simple, standard way to monitor and manage resources, with a clear structure and design pattern for how to define a resource. It monitors and manages Java application running status, device and resource information, and Java VIRTUAL machine running status. JMX is dynamic, so you can monitor and manage resources dynamically when they are created, installed, and implemented. The JDK comes with JConsole, which uses JMX technology to monitor resources.

With JMX technology, a Java object called an MBean or MXBean is defined to represent the specified resource to be managed, and the resource information can then be registered with the MBean Server to provide services externally. MBean Server acts as an agent to provide services externally and manage MBean resources internally. Such an elegant design allows MBean resource management and MBean Server agent to be completely independent, allowing it to freely control MBean resource information.

JMX is not just for local administration; the JMX Remote API adds Remote capabilities to JMX to remotely monitor and manage applications over a network.

2. Why use JMX technology?

JMX technology provides Java developers with a simple, flexible, and standard way to monitor Java applications. Thanks to its relatively independent architectural design, JMX can be smoothly integrated into various monitoring systems.

Here are a few specific benefits of JMX:

  1. Out-of-the-box monitoring. JMX is a standard part of the Java SE. It provides basic management functions such as resource management, service hosting, and remote monitoring.
  2. JMX technology provides a general and standard management mode of resources, systems, applications and networks, which can be used locally or remotely. It can also be extended to other scenarios, such as Java EE applications.
  3. JMX technology provides the ability to monitor the state of the JVM, which is already built into JMX and can be easily monitored and managed.
  4. The JMX architecture is well designed, and the componentized design can be extended freely.
  5. JMX technology strictly adheres to existing Java specifications such as the JNDI specification.
  6. JMX can be freely integrated with other management solutions, and thanks to the open JMX API, resources in JMX can be managed through Web services.

3. Technical architecture of JMX

JMX technology architecture is mainly composed of resource management module (MBean/MXBean), resource broker module (MBean Server), and Remote management module (Remote API). The following picture from Wikipedia shows the relationship between the three modules.

3.1. Resource management MBeans

Resource management is identified as the Probe Level in the architecture. In JMX, mBeans or MXBeans are used to represent a resource (hereinafter referred to as MBeans), and resources are accessed and managed through Mbeans. So mBeans often contain the properties and operation methods of resources.

JMX already has multidimensional resource detection for the JVM, so it is easy to start a JMX agent to access the built-in JVM resource detection to remotely monitor and manage the JVM through JMX technology.

The following list of JMX resource detection classes for the JVM can be used directly.

The resource interface Managed Resources Object Name Number of instances in the VM
ClassLoadingMXBean Class loading java.lang:type= ClassLoading 1
CompilationMXBean Assembly system java.lang:type= Compilation Zero or one
GarbageCollectorMXBean Garbage collection java.lang:type= GarbageCollector, name=collectorName One or more
LoggingMXBean Logging system java.util.logging:type =Logging 1
MemoryManagerMXBean Memory pool java.lang: typeMemoryManager, name=managerName One or more
MemoryPoolMXBean memory java.lang: type= MemoryPool, name=poolName One or more
MemoryMXBean Memory system java.lang:type= Memory 1
OperatingSystemMXBean The operating system java.lang:type= OperatingSystem 1
RuntimeMXBean Run-time system java.lang:type= Runtime 1
ThreadMXBean Thread system java.lang:type= Threading 1

The following code example demonstrates the use of JMX to detect some JVM information.

package com.wdbyte.jmx;

import java.lang.management.CompilationMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryManagerMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.util.List;
import java.util.stream.Collectors;

/**
 * JMX JVM
 *
 * @author https://www.wdbyte.com
 */
public class JavaManagementExtensions {

    public static void main(String[] args) {
        OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        String osName = operatingSystemMXBean.getName();
        String osVersion = operatingSystemMXBean.getVersion();
        int processors = operatingSystemMXBean.getAvailableProcessors();
        System.out.println(String.format("OS: %s, version: %s, Processor: % D", osName, osVersion, processors));

        CompilationMXBean compilationMXBean = ManagementFactory.getCompilationMXBean();
        String compilationMXBeanName = compilationMXBean.getName();
        System.out.println("Compiling system:" + compilationMXBeanName);

        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        long max = heapMemoryUsage.getMax();
        long used = heapMemoryUsage.getUsed();
        System.out.println(String.format("Memory usage: %dMB/%dMB", used / 1024 / 1024, max / 1024 / 1024));

        List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
        String gcNames = gcMXBeans.stream()
            .map(MemoryManagerMXBean::getName)
            .collect(Collectors.joining(","));
        System.out.println("Garbage collector:"+ gcNames); }}Copy the code

The following results can be obtained:

Operating system: Mac OS X, version 11.6, Processor: 12 Compilation system: HotSpot 64-bit Tiered Compilers Use memory: 3MB/4096MB garbage collector: G1 Young Generation,G1 Old GenerationCopy the code

3.2. Resource proxy MBean Server

Resource broker MBean Server is a proxy for MBean resources. MBean Resources can be used for remote management through MBean Server. MBean resources and MBean Server are often in the same JVM, but this is not required.

In order for MBean Server to manage MBean resources, resources must first be registered with MBean Server, and any JMX-compliant MBean resource can be registered. Finally, MBean Server exposes a remote communication interface to provide services externally.

3.3. JMX Remote management

JMX API can be accessed through network protocols, such as HTTP, SNMP (Network Management Protocol), RMI remote call protocol, etc. JMX technology implements RMI remote call protocol by default.

Thanks to the full decoupling of resource management MBeans, it is easy to extend resource management capabilities to other protocols, such as web page management over HTTP.

4. Specific use of JMX

Using JMX to get JVM running information was demonstrated in the Resource Management MBeans section, so what if you want to customize a resource MBean?

Here is an example that simulates a memory resource MBean and finally manages it remotely.

4.1. Write resource management MBeans

Mbeans must be written in accordance with JMX design specifications. Mbeans are much like special Java beans in that they require an interface and an implementation class. The MBean resource interface always ends with an MBean or MXBean, and the implementation class is named after the interface removes the MBean or MXBean.

Write a memory resource management MBean interface defined as follows:

package com.wdbyte.jmx;

/ * * *@author https://www.wdbyte.com
 */
public interface MyMemoryMBean {

    long getTotal(a);

    void setTotal(long total);

    long getUsed(a);

    void setUsed(long used);

    String doMemoryInfo(a);
}
Copy the code

Then implement this interface:

package com.wdbyte.jmx;

/ * * *@author https://www.wdbyte.com
 */
public class MyMemory implements MyMemoryMBean {

    private long total;
    private long used;

    @Override
    public long getTotal(a) {
        return total;
    }

    @Override
    public void setTotal(long total) {
        this.total = total;
    }

    @Override
    public long getUsed(a) {
        return used;
    }

    @Override
    public void setUsed(long used) {
        this.used = used;
    }

    @Override
    public String doMemoryInfo(a) {
        return String.format("Memory usage: %dMB/%dMB", used, total); }}Copy the code

This example has only two long primitives in myMemory.java, so the interface ends with an MBean. If the attributes in the resource implementation class are references to the custom entity class, then the interface needs to end with an MXBean.

This completes the creation of thread-number resource MBeans, where total and Used are resource properties and doMemoryInfo is resource operation method.

4.2. Register resources with MBean Server

From the JMX architecture diagram above, we know that MBean resources need to be registered with MBean Server for proxy before they can be exposed to external calls. Therefore, we want to remotely manage our custom MyMemory resources by proxy first.

package com.wdbyte.jmx;

import java.lang.management.ManagementFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

/ * * *@author https://www.wdbyte.com
 */
public class MyMemoryManagement {

    public static void main(String[] args) throws MalformedObjectNameException, NotCompliantMBeanException,
        InstanceAlreadyExistsException, MBeanRegistrationException, InterruptedException {
        // Get the MBean Server
        MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
        MyMemory myMemory = new MyMemory();
        myMemory.setTotal(100L);
        myMemory.setUsed(20L);
        / / register
        ObjectName objectName = new ObjectName("com.wdbyte.jmx:type=myMemory");
        platformMBeanServer.registerMBean(myMemory, objectName);

        while (true) {
            // Prevent exit
            Thread.sleep(3000); System.out.println(myMemory.doMemoryInfo()); }}}Copy the code

After startup, you can see that the console prints our custom memory information every three seconds.

Used memory: 20MB/100MB used memory: 20MB/100MBCopy the code

Starting a Java program without any JVM parameters, JMX can only be accessed on the current machine, and if you want to access it remotely over the network, you need to specify the current machine IP and open port at startup.

$ java -Dcom.sun.management.jmxremote=true \  Enable remote access- Dcom. Sun. Management. Jmxremote. Port = 8398 \ # custom JMX port - Dcom. Sun. Management jmxremote. SSL = false \ # whether to use the SSL protocol, Production must be open - Dcom. Sun. Management jmxremote. Authenticate = false \ # do you need certification, The production environment must open - Djava. Rmi. Server hostname = 150.158.2.56 YourClass. Java IP # current machineCopy the code

4.3. Manage JConsole remotely

Jconsole is a Java monitoring and management tool based on JMX technology. If JDK environment variables have been configured, you can run the jConsole command to start the tool.

After jConsole is started, Java processes on the current machine are displayed. In this case, the Java process you want to monitor is displayed. After connection, an insecure protocol is displayed because HTTPS is not configured for Java programs when they are started by default.

After the connection, you can see multidimensional JVM monitoring information, which is obtained by reading JVM resource MBean information.

The thread information is listed on the following page. Note the thread information at the bottom, where you can see the RMI TCP thread, which also proves that JMX is managed remotely by default over the RMI protocol.

On the MBean page, you can browse all the managed MBean information, see the memory information in our custom com.wdbyte.jmx, and even directly modify the used variable in it.

The console log changes immediately after the modification. You can see that the modification is successful.

Used memory: 20MB/100MB used memory: 20MB/100MB used memory: 30MB/100MBCopy the code

You can call the doMemoryInfo method during the operation and see that the memory used in the return value has been updated from 20MB at startup to 30MB.

As always, the code samples in the current article are housed at github.com/niumoo/Java… .

Current series:

  1. Arthas – Java’s ultimate tool for online problem location processing
  2. Java benchmarking using JMH
  3. Overview of monitoring and management in Java
  4. Monitor and manage Java programs using JMX

Reference:

  • Docs.oracle.com/en/java/jav…

After < >

Hello world:) I’m Aaron, a tech tool guy on the front line.

This article is constantly updated, you can follow the public account “Program Ape Alang” or visit the unread code blog (https://www.wdbyte.com).

This article Github.com/niumoo/Java… Welcome to Star!