In Arthas Series 2, Ali lists all java processes on the machine in this way

catalogue

Click like and watch again, form the habit of praise, search on wechat [coriander Chat Game] and pay attention to me.    

1. How to check code based on Performance

2. How to implement your own java process list

3. Step by step implementation code

4. Summary:

Click like and watch again, form the habit of praise, search on wechat [coriander Chat Game] and pay attention to me.    

 

Today, let's learn how Arthas prints out all Java threads on the current machine and calls the console. This technical point is not clear. We can find out the implementation from the code of Arthas, learn the knowledge points, and have ideas when we use it next time. However, the amount of code of Arthas is so large that how to read the code when no one brings it?

1. How to check code based on Performance

1.1 debugging breakpoints, because I have introduced how to debug in the previous article, the code that can be debugged must be debugged, and the power-off tracking code, so I also want to track the code in the way of debugging, but when I hit the breakpoint and use the command, I found that the breakpoint did not take effect after startup. Think about why it did not take effect? The last article has the answer, the principle of the debugger.

java -jar arthas-boot.jar

1.2 code reading: since you want to read the code, you can't be afraid to read the code. Reading the code doesn't need any environment, no testing, and no conditions. Just follow the direction of the code. Take a small book and record your understanding.

1.3 examples

See the printed log as follows. Since you want to see its source code, print from the running log and analyze the content of the log. It is found that the printed log has no parameters and can be copied directly. Don't think so much. Search globally and find many uses below. We can see that many places are not code calls. We can directly locate Arthas boot. OK, we have found the source of this code and directly enter the understanding stage.

2. How to implement your own java process list

In the process of tracking the code, we should also clarify the ideas, how the author did it, and what kind of ideas you would have if it was you. If your ideas happen to coincide with those of the author, I believe you understand the code very simply. If your ideas are different from those of the author, we should think about why the author of Arthas did so, Is your plan better? It's better to believe in books than to have no books! Let's start with a question.

1. How to find jps when accessing environment variables

1.1 how to read the environment variable of the computer: system getProperty("java.home")

1.2 what is jps? jps is a command provided by java to display the pid of all current Java processes. We found the core of the matter.

1.3 how to find jps? The path of jps may be different, or the system that Arthas runs is different. The author directly lists all possible paths, and there is always one subject to approval.

private static File findJps() {
       // Try to find jps under java.home and System env JAVA_HOME
       String javaHome = System.getProperty("java.home");
       String[] paths = { "bin/jps", "bin/jps.exe", "../bin/jps", "../bin/jps.exe" };

       List<File> jpsList = new ArrayList<File>();
       for (String path : paths) {
           File jpsFile = new File(javaHome, path);
           if (jpsFile.exists()) {
               AnsiLog.debug("Found jps: " + jpsFile.getAbsolutePath());
               jpsList.add(jpsFile);
          }
      }
    //Unimportant code is omitted
}

2. jps command format

Problem: execution format of jps command

There are two ways to look at jps in the code. One is to add V for more information, and the other is not to add V, which only lists all threads.

  String[] command = null;
      if (v) {
          command = new String[] { jps, "-v", "-l" };
      } else {
          command = new String[] { jps, "-l" };
      }

      List<String> lines = ExecutingCommand.runNative(command);

3. Run cmd

We see that Arthas runs in the console window. Our problem is:

3.1 how to execute the command? Use the exec interface of runtime to call system commands directly

3.2 what is process? Process represents a process, and the console window launched is a process


  public static List<String> runNative(String[] cmdToRunWithArgs) {
       Process p = null;
       try {
           p = Runtime.getRuntime().exec(cmdToRunWithArgs);

4. Read output and number

Code location: com taobao. arthas. common. ExecutingCommand#runNative(java.lang.String[])

Question: how to read the output of the console window, or take over the console window, and use process Getinputstream() gets the output of the console.

ArrayList<String> sa = new ArrayList<String>();
      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      try {
          String line;
          while ((line = reader.readLine()) != null) {
              sa.add(line);
          }

3. Step by step implementation code

  1. The core technology is to call JPS Exe command

  2. How to execute commands

    jps -l

     

  3. Output console output

    Full code:

package com.taobao.arthas.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* Get all Java threads on the machine

* @author coriander
*/
public class Aain {
   public static void main(String[] args) throws IOException {
       //1. Get the jps address. After execution, you can check whether there is jps under the corresponding path exe
       String jpsPath = getJpsPath();
       //2. Run cmd
       runCmd(jpsPath);

  }

   /**
    * Read output
    * @param reader
    * @throws IOException
    */
   private static void readOutput(BufferedReader reader) throws IOException {
       try {
           String line;
           while ((line = reader.readLine()) != null) {
               System.out.println(line);
          }
      } catch (Exception e) {
           e.printStackTrace();
      } finally {
           reader.close();
      }
  }

   /**
    * Run cmd
    * @param jpsPath
    * @throws IOException
    */
   private static void runCmd(String jpsPath) throws IOException {
       String[] cmdStr =  new String[] { jpsPath, "-l" };
       Process p = null;
       try {
           p = Runtime.getRuntime().exec(cmdStr);
      } catch (Exception e) {
           return;
      }
       readOutput(new BufferedReader(new InputStreamReader(p.getInputStream())));
  }

   /**
    * Get JPS Exe address
    * @return
    */
   private static String getJpsPath() {
       String javaHome = System.getProperty("java.home");
       // Because it is demonstrated in windows environment, it only deals with window environment
       return new File(javaHome, "../bin/jps.exe").getAbsolutePath();
  }
}

Operation results:

4. Summary:

The initial solution of each problem is very simple. It only becomes the final solution because of the addition of exception handling, special requirements, or more comprehensive. We should see the essence of technology from complex code, rather than getting lost in a large number of code.

Today I mainly learned how to call the console, read the console output, and use jps. Do you understand?

Recommended reading # click the title to jump

1,Build debugging environment for Arthas series I

2,With these software, writing code has a flying speed

3,Learn these debugging skills first, and then write code, which can improve the efficiency ten times. Spit blood!

 

Welfare time

Keywords: Java Programming arthas

Added by cdorob on Thu, 10 Feb 2022 08:19:57 +0200