Java diagnostic artifact: 6 to flying Arthas, these functions are arranged quickly!

1 Introduction

What is Arthas?

Excerpt from an official introduction on Github

Java diagnostic artifact: 6 to flying Arthas, these functions are arranged quickly!

 

Alibaba Arthas is a diagnostic tool that enables us to monitor, analyze and diagnose Java applications. One of the main benefits of using Arthas is that we don't need to change the code or even restart the Java service to be monitored.

In this article, we will install Arthas first, and then conduct a case study to demonstrate some key features of Arthas.

Finally, because Arthas is written in Java, it is cross-platform and can run normally on Linux, macOS and Windows.

2. Download and get started

First, let's start downloading the Arthas library directly through the download link or using curl:

curl -O https://alibaba.github.io/arthas/arthas-boot.jar

Now, let's run Arthas with the -h (help) option to test whether it works properly:

java -jar arthas-boot.jar -h

If successful, we should see the help guide for all the display commands:

Java diagnostic artifact: 6 to flying Arthas, these functions are arranged quickly!

 

3. Case study

Throughout the tutorial, we will use a very simple application based on a rather inefficient implementation of the Fibonacci sequence using recursion:

public class FibonacciGenerator {
     public static void main(String[] args) {
        System.out.println("Press a key to continue");
        System.in.read();
        for (int i = 0; i < 100; i++) {
            long result = fibonacci(i);
            System.out.println(format("fib(%d): %d", i, result));
        }    }     public static long fibonacci(int n) {
        if (n == 0 || n == 1) {
            return 1L;
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }    }}

The most interesting part of this example is that Fibonacci follows the mathematical definition of Fibonacci numbers.

In the main method, we use for loops with larger numbers, so our computer will be busy with longer calculations.

4. Start Arthas

Now, let's try Arthas! The first thing we need to do is to run our small Fibonacci application. For this, we can use our favorite IDE or run it directly in the terminal. It will require pressing a key to start, after attaching the process to Arthas, we will press any key.

Now, let's run the Arthas executable file:

java -jar arthas-boot.jar

Arthas will prompt a menu to select the process we want to attach to:

[INFO] arthas-boot version: 3.1.7
[INFO] Found existing java process, please choose one and hit RETURN.
* [1]: 25500 com.baeldung.arthas.FibonacciGenerator
...

Let us choose a name called com.baeldung.arthas.FibonacciGenerator. Just enter a number in the list, in this example "1", and press Enter.

Arthas will now follow this process and begin:

INFO] Try to attach process 25500
[INFO] Attach process 25500 success.
...                    

Once we have launched Arthas, we will prompt you to issue different commands.

We can use the help command to get more information about the available options. In addition, in order to facilitate the use of Arthas, we can also use the Tab key to automatically complete its commands.

After attaching Arthas to our process, we can now press a key and the program will start printing Fibonacci numbers.

5. Dashboard

Once Arthas is launched, we can use the dashboard. In this case, we continue by typing the dashboard command. Now, we see a detailed screen with several panes and a lot of information about the Java process:

Java diagnostic artifact: 6 to flying Arthas, these functions are arranged quickly!

 

Learn about some of them in more detail:

  1. The top is dedicated to the currently running thread
  2. One of the important columns is the CPU consumption of each thread
  3. Section 3 shows the CPU time of each thread
  4. Another interesting pane is for memory analysis. The different memory areas and their statistics are listed. On the right, we have information about the garbage collector
  5. Finally, in Section 5, we provide information about the host platform and JVM.

You can exit the dashboard by pressing q .

It should be remembered that even if we quit, Arthas will still be attached to this process. Therefore, in order to properly disconnect it from our process, we need to run the stop command .

6. Analyze the stack trace

In the dashboard, we see that our main process takes almost 100% of the CPU. The ID of this process is 1, and we can see it in the first column.

Now that we have exited the dashboard, we can analyze the process in more detail by running the thread command :

thread 1

The number passed as a parameter is the thread ID. Not surprisingly, Arthas will print out the stack trace, which is confusing to call the fibonacci method.

If the stack trace is long and cumbersome, then the thread command allows us to use pipes:

thread 1 | grep 'main('

This will only print the lines that match the grep command:

[arthas@25500]$ thread 1 | grep 'main('
    at com.baeldung.arthas.FibonacciGenerator.main(FibonacciGenerator.java:10)

7. Decompile Java classes

Imagine a scenario in which we are analyzing a Java application that we know little or nothing, and then suddenly find that the stack is full of repeated calls of the following types:

[arthas@59816]$ thread 1
"main" Id=1 RUNNABLE
  at app//com.baeldung.arthas.FibonacciGenerator.fibonacci(FibonacciGenerator.java:18)
  at app//com.baeldung.arthas.FibonacciGenerator.fibonacci(FibonacciGenerator.java:18)
  ...

Since we are running Arthas, we can decompile a class to view its contents. To this end, we can use the jad command to pass the qualified class name as a parameter:

jad com.baeldung.arthas.FibonacciGenerator
 ClassLoader:+-jdk.internal.loader.ClassLoaders$AppClassLoader@799f7e29
  +-jdk.internal.loader.ClassLoaders$PlatformClassLoader@60f1dd34
 Location:/home/amoreno/work/baeldung/tutorials/libraries-3/target/
/*
 * Decompiled with CFR.
 */
package com.baeldung.arthas;
 import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
 public class FibonacciGenerator {
    public static void main(String[] arrstring) throws IOException {
   
   

The output is the decompiled Java class and some useful metadata, such as the location of the class . This is a very useful and powerful feature.

8. Search categories and search methods

The search class command is very useful when searching for classes loaded in the JVM. We can use it by typing sc and passing a pattern with or without wildcards as a parameter :

[arthas@70099]$ sc *Fibonacci*
com.baeldung.arthas.FibonacciGeneratorAffect(row-cnt:1) cost in 5 ms.

Once you have a qualified name for the class, you can use two additional signs to find more information:

  • -d display class details
  • -f display class field

However, the fields of the class must be queried together with the detailed information:

[arthas@70099]$ sc -df com.baeldung.arthas.FibonacciGenerator
  class-info        com.baeldung.arthas.FibonacciGenerator
  ...

Similarly, we can use the command sm (search method) to find the loaded method in the class. In this case, for our class com.baeldung.arthas.FibonacciGenerator, we can run:

[arthas@70099]$ sm com.baeldung.arthas.FibonacciGenerator
com.baeldung.arthas.FibonacciGenerator <init>()V
com.baeldung.arthas.FibonacciGenerator main([Ljava/lang/String;)Vcom.baeldung.arthas.FibonacciGenerator fibonacci(I)JAffect(row-cnt:3) cost in 4 ms.

We can also use the flag -d to retrieve detailed information about the method . Finally, we can pass an optional parameter for the method name to reduce the number of methods returned:

sm -d com.baeldung.arthas.FibonacciGenerator fibonacci
 declaring-class  com.baeldung.arthas.FibonacciGenerator
 method-name      fibonacci
 modifier         public,static
 annotation
 parameters       int
 return           long
 exceptions
 classLoaderHash  799f7e29

9. Monitoring method calls

Another cool thing we can do with Arthas is surveillance methods. This can be very convenient when debugging performance issues in an application . For this, we can use the monitor command .

The monitor command requires a flag -c <sec> and two parameters-the qualified class name and method name.

For our case study, let's now call the monitor:

monitor -c 10 com.baeldung.arthas.FibonacciGenerator fibonacci

As expected, Arthas will print indicators about the fibonacci method every 10 seconds:

Affect(class-cnt:1 , method-cnt:1) cost in 47 ms.
 timestamp            class                                          method     total   success  fail  avg-rt(ms)  fail-rate                                                                      
-----------------------------------------------------------------------------------------------------------------------------                                                                     
 2020-03-07 11:43:26  com.baeldung.arthas.FibonacciGenerator  fibonacci  528957  528957   0     0.07        0.00%
...                                                                          

We also have indicators for those calls that eventually fail-these are very useful for debugging.

10. Monitoring method parameters

If you need to debug the parameters of the method, you can use the watch command . However, the syntax is a bit complicated:

watch com.baeldung.arthas.FibonacciGenerator fibonacci '{params[0], returnObj}' 'params[0]>10' -n 10

Let us understand each parameter in detail:

  • The first parameter is the class name
  • The second is the method name
  • The third parameter is an OGNL expression, used to define what we want to watch-in this case, it is the first (and only) method parameter and the return value
  • The fourth and last optional parameter is a boolean expression used to filter the calls we want to monitor

For this example, we only want to monitor parameters greater than 10. Finally, we add a flag to limit the number of results to 10:

watch com.baeldung.arthas.FibonacciGenerator fibonacci '{params[0], returnObj}' 'params[0]>10' -n 10
Press Q or Ctrl+C to abort.Affect(class-cnt:1 , method-cnt:1) cost in 19 ms.
ts=2020-02-17 21:48:08; [cost=30.165211ms] result=@ArrayList[
    @Integer[11],
    @Long[144],
]
ts=2020-02-17 21:48:08; [cost=50.405506ms] result=@ArrayList[
    @Integer[12],
    @Long[233],
]
...

Here, we can see examples of calls with CPU time and input/return values.

11. Probe

The profiler command can provide very intuitive functions for those interested in application performance . The profiler will evaluate the performance of the CPU that our process is using.

Let's run the profiler by starting profiler start. This is a non-blocking task, which means we can continue to use Arthas while the profiler is working.

At any time, we can ask how many samples the profiler has by running profiler getSamples.

Now let's use the profiler stop to stop the profiler. At this point, the FlameGraph image will be saved. In this case, we have a chart in which the Fibonacci line dominates.

Java diagnostic artifact: 6 to flying Arthas, these functions are arranged quickly!

 

Note that this chart may be particularly useful when we want to detect where the CPU time is spent.

12. Conclusion

In this article, we explored some of the most powerful and useful features of Arthas.

As we have seen, Arthas has many commands to help us diagnose various problems. It is also particularly useful when we cannot double-check the code that accesses the application, or when we want to quickly diagnose a problematic application running on the server.
The source code is available on Github.

Guess you like

Origin blog.csdn.net/python8989/article/details/108468263