Wechat public number: code on the public number of the article name: Thread pool monitoring – simple version

Java thread pool must be familiar to everyone, for some concurrent tasks can be executed, we give priority to consider the thread pool operation, but for some of the indicators out of the problem, we are difficult to troubleshoot, here with you a simple version of the thread pool monitoring.

ThreadPoolExecutor

In the native thread pool, many of the variables we want to monitor are private (full of malicious intent), but some provide get methods to help us get (except for the health field).

If we want to achieve the effect of monitoring, we need to extend this, not just get method field monitoring. At this point, there are two methods in the native thread pool:

  1. beforeExecute(Thread t, Runnable r)

The method is executed before the task is executed.

  1. afterExecute(Runnable r, Throwable t)

This method is executed after the task is executed (must be executed, placed ina finally statement).

We can add additional operations to these two methods to help us monitor other metrics.

MBean

MBean is a standard JavaBean, through integration and implementation of a set of standard Bean interface, this is called MBean, MBean registered in MBeanServer. (Think of it as a Bean that the JVM allows for state-assisted queries.)

In this Demo, I am through the form of MBean to monitor indicators, so also help you to understand it.

Here, I use HtmlAdaptorServer to display the corresponding MBean information.

The key code

  1. beforeExecute
 protected void beforeExecute(Thread t, Runnable r) {
         // Record the start time of each execution
        startTime.set(System.currentTimeMillis());
    }
Copy the code
  1. afterExecute
 protected void afterExecute(Runnable r, Throwable t) {
        long costTime = System.currentTimeMillis() - startTime.get(); // Compute tasks take time
        startTime.remove(); // Clear the start time
        maxCostTime = Math.max(maxCostTime, costTime);
        if (totalTasks.get() == 0) {
            minCostTime = costTime;
        }
        minCostTime = Math.min(minCostTime, costTime);
        totalCostTime.addAndGet(costTime);
        totalTasks.incrementAndGet();
        activeCount = this.getActiveCount();
}
Copy the code
  1. registerMBean
    public static void registerMBean(Object obj, ObjectName objectName) {
        try {
            // Register MBean information
            server.registerMBean(obj, objectName);
        } catch(InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { e.printStackTrace(); }}Copy the code

rendering

Montos-threadpool-monitoring Welcome star and Fork.

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign