Arthas,一个JAVA项目分析/诊断工具在mac上的试用记录

之前看到的一个分析java项目的工具arthas,最近有时间试用整理下。用熟了就可以分析很多问题了,岂不美哉。虽然已经有很多分析工具 jvisualvm,jstat,jmap,jstack,Eclipse Memory Analyzer等。但可能不是大杂烩,或者线上无法分析等。所以看看arthas的功能,好用就用它了。

Arthas简介

Arthas 是Alibaba开源的Java诊断工具,深受开发者喜爱。当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决:

  • 这个类从哪个 jar 包加载的?为什么会报各种类相关的 Exception?
  • 我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?
  • 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?
  • 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!
  • 是否有一个全局视角来查看系统的运行状况?
  • 有什么办法可以监控到JVM的实时运行状态?
  • 怎么快速定位应用的热点,生成火焰图?

Arthas支持JDK 6+,支持Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的 Tab 自动补全功能,进一步方便进行问题的定位和诊断。

Arthas,一个JAVA项目分析/诊断工具在mac上的试用记录_第1张图片

扩展:java Instrumentation指的是可以用独立于应用程序之外的代理(agent)程序来监测和协助运行在JVM上的应用程序。这种监测和协助包括但不限于获取JVM运行时状态,替换和修改类定义等。 Arthas 的整体逻辑也是在 Java 的Instrumentation基础上来实现。

参考:(JAVA Instrumentation)https://blog.csdn.net/productshop/article/details/50623626
(Arthas 源码原理)https://blog.csdn.net/chainhou/article/details/105007699

Arthas的操作流程(简易)

官方提供了两种使用方式 下载arthas-boot.jar 或者直接安装使用 as. sh。 这里说明前一种。

一、下载arthas-boot.jar

打开命令行操作

chl> $ curl -O https://alibaba.github.io/arthas/arthas-boot.jar
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:43 --:--:--     0

会将目标文件下载到当前目录中。

二、运行arthas-boot.jar

可以看到执行 java -jar arthas-boot.jar之后,它罗列了当前的java进程供你选择,选择之后,就可以对该进程进行监控了。(也可以直接增加pid监控,如:java -jar arthas-boot.jar pid)。 在选择好pid之后,它首先会将 arthas所需要的jar相关文件进行下载,然后做一些初始化的工作。

chl> $ java -jar arthas-boot.jar 
[INFO] arthas-boot version: 3.1.8
[INFO] Process 7457 already using port 3658
[INFO] Process 7457 already using port 8563
[INFO] Found existing java process, please choose one and input the serial number of the process, eg : 1. Then hit ENTER.
* [1]: 7457 org.apache.zookeeper.server.quorum.QuorumPeerMain
  [2]: 304 
  [3]: 9628 
1
[INFO] Start download arthas from remote server: https://maven.aliyun.com/repository/public/com/taobao/arthas/arthas-packaging/3.1.8/arthas-packaging-3.1.8-bin.zip
[INFO] File size: 10.82 MB, downloaded size: 1.60 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 2.17 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 2.81 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 3.39 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 3.90 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 4.53 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 4.96 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 5.63 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 6.32 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 6.89 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 7.43 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 8.00 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 8.64 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 8.88 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 9.11 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 9.40 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 9.89 MB, downloading ...
[INFO] File size: 10.82 MB, downloaded size: 10.40 MB, downloading ...
[INFO] Download arthas success.
[INFO] arthas home: /Users/chenhailong/.arthas/lib/3.1.8/arthas
[INFO] The target process already listen port 3658, skip attach.
[INFO] arthas-client connect 127.0.0.1 3658
  ,---.  ,------. ,--------.,--.  ,--.  ,---.   ,---.                           
 /  O  \ |  .--. ''--.  .--'|  '--'  | /  O  \ '   .-'                          
|  .-.  ||  '--'.'   |  |   |  .--.  ||  .-.  |`.  `-.                          
|  | |  ||  |\  \    |  |   |  |  |  ||  | |  |.-'    |                         
`--' `--'`--' '--'   `--'   `--'  `--'`--' `--'`-----'                          
                                                                                

wiki      https://alibaba.github.io/arthas                                      
tutorials https://alibaba.github.io/arthas/arthas-tutorials                     
version   3.1.8                                                                 
pid       7457                                                                  
time      2020-04-08 10:59:25                                                   

[arthas@7457]$ 

注:最后一行‘[arthas@7457]$’ ,说明打开进入了监控客户端,在这里就可以执行相关命令进行查看了。 可以使用quit(退出当前客户端)、stop\shutdown(关闭arthas服务端,并退出所有客户端)。除了在命令行查看外,还可以通过浏览器访问http://127.0.0.1:8563/查看。如下图:

arthas浏览器访问

当我们在shell端执行quit,并重新java -jar arthas-boot.jar 7457当前进程后。会有这样一个提示(表示目标进程已被监听,跳过attach):

The target process already listen port 3658, skip attach.

attach机制:Java提供了attach机制。通过attach机制,我们可以直接attach到目标JVM进程,然后进行一些操作,比如获取内存dump、线程dump,类信息统计(比如已加载的类以及实例个数等),动态加载agent,动态设置vm flag(但是并不是所有的flag都可以设置的,因为有些flag是在jvm启动过程中使用的,是一次性的),打印vm flag,获取系统属性等。

attach简介及示例参考:https://www.jianshu.com/p/39d189961773


这里是下载好之后的文件列表,也就是直接执行第二种安装方式‘curl -L https://alibaba.github.io/arthas/install.sh | sh’安装的文件。

chl> $ ls
arthas-agent.jar	arthas-client.jar	arthas-demo.jar		arthas.properties	as.bat			async-profiler		logback.xml
arthas-boot.jar		arthas-core.jar		arthas-spy.jar		as-service.bat		as.sh			install-local.sh
chl> $ pwd
/Users/chenhailong/.arthas/lib/3.1.8/arthas

客户端保持30分钟内有效,超时即会过期,需要重新连接

[arthas@7457]$ session (c8efe0df-0343-4cf0-bec8-c5f57865e3c1) is closed because session is inactive for 30 min(s).

三、操作arthas

通过输入help可以看到,Oh My God!~~~~,提供了这么多的功能。而且做的很友好,有tab自动补全功能,
以下列表中标有注1的需要知道,这些命令通过asm字节码增强技术来实现,会在指定的方法中插入一些切面来实现数据统计及观测功能。因此在线上、预发环境使用时,要明确需要观测的类、方法及条件。诊断结束后要shutdown或者执行reset命令。

[arthas@7457]$ help
 NAME         DESCRIPTION
 ## 显示帮助
 help         Display Arthas Help
 ## 显示快捷键列表
 keymap       Display all the available keymap for the specified connection.
 ## 查看JVM已经加载的类信息
 sc           Search all the classes loaded by JVM
 ## 查看JVM已经加载的类的方法的信息
 sm           Search the method of classes loaded by JVM
 ## 查看类加载器信息
 classloader  Show classloader info
 ## 反编译类文件
 jad          Decompile class
 ## 查看类的静态属性
 getstatic    Show the static field of a class
 ## 方法监控(注1)
 monitor      Monitor method execution statistics, e.g. total/success/failure count, average rt, fail rate, etc.
 ## 方法的调用路径(注1)
 stack        Display the stack trace for the specified class and method
 ## 显示当前的jvm线程信息
 thread       Display thread info, thread stack
 ## 方法内部调用路径,并输出方法路径上的每个节点耗时(注1)
 trace        Trace the execution time of specified method invocation.
 ## 方法的执行信息监测(注1)
 watch        Display the input/output parameter, return object, and thrown exception of specified method invocation
 ## 方法 执行数据的时空隧道,记录下指定方法每次调用的入参和返回信息,并能对这些不同的时间下调用进行观测(注1)
 tt           Time Tunnel
 ## 显示当前的jvm信息
 jvm          Display the target JVM information
 perfcounter  Display the perf counter infornation.
 ognl         Execute ognl expression.
 mc           Memory compiler, compiles java files into bytecode and class files in memory.
 redefine     Redefine classes. @see Instrumentation#redefineClasses(ClassDefinition...)
 ## 监控目标系统的实时数据版面,包括jvm,thread,gc,vm等
 dashboard    Overview of target jvm's thread, memory, gc, vm, tomcat info.
 ## dump已经加载的类的信息
 dump         Dump class byte array from JVM
 heapdump     Heap dump
 ## 查看或更改arthas设置
 options      View and change various Arthas options
 ## 清屏
 cls          Clear the screen
 ## 重置增强类,将被arthas增强过的类全部还原
 reset        Reset all the enhanced classes
 ## 输出arthas版本信息
 version      Display Arthas version
 ## 查看当前会话信息
 session      Display current session information
 ## 显示、修改JVM系统熟悉信息
 sysprop      Display, and change the system properties.
 sysenv       Display the system env.
 vmoption     Display, and update the vm diagnostic options.
 ## 打印日志级别
 logger       Print logger info, and update the logger level
 ## 显示命令执行记录
 history      Display command history
 cat          Concatenate and print files
 echo         write arguments to the standard output
 pwd          Return working directory name
 mbean        Display the mbean information
 ## 管道操作
 grep         grep command for pipes.
 tee          tee command for pipes.
 profiler     Async Profiler. https://github.com/jvm-profiling-tools/async-profiler
 ## 关闭服务端
 stop         Stop/Shutdown Arthas server and exit the console.

这里就挑几个常用的命令进行展示:

  • dashboard:查看jvm\线程\env基本信息
  • thread:查看线程的运行状态
  • jad:反编译class文件[通过自动补全,查找上线代码是否包含自己新增的功能,很方便]

!!!【以下的这几个通过简单测试代码进行试用】

  • sc:查看jvm中已经加载的类信息
  • stack:调用栈信息
  • Track:观察方法执行的时候哪个子调用比较慢:
  • watch:观察方法的执行入参
  • monitor:监控某个特殊方法的调用统计数据,包括总调用次数,平均rt,成功率等信息,每隔5秒输出一次。

3.1 dashboard

主要展示了三部分内容,线程,jvm,java-env。每过几秒会自动刷新


## 线程部分
ID               NAME                                               GROUP                             PRIORITY         STATE            %CPU             TIME             INTERRUPTED      DAEMON           
64               Timer-for-arthas-dashboard-97244c33-b0c9-4f81-b9a5 system                            10               RUNNABLE         100              0:0              false            true             
15               Attach Listener                                    system                            9                RUNNABLE         0                0:0              false            true             
3                Finalizer                                          system                            8                WAITING          0                0:0              false            true             
11               NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181          main                              5                RUNNABLE         0                0:2              false            true             
14               ProcessThread(sid:0 cport:2181):                   main                              5                WAITING          0                0:0              false            false            
10               RMI TCP Accept-0                                   system                            5                RUNNABLE         0                0:0              false            true             
2                Reference Handler                                  system                            10               WAITING          0                0:0              false            true             
12               SessionTracker                                     main                              5                TIMED_WAITING    0                0:1              false            false            
4                Signal Dispatcher                                  system                            9                RUNNABLE         0                0:0              false            true             
13               SyncThread:0                                       main                              5                WAITING          0                0:0              false            false            
46               arthas-shell-server                                system                            9                TIMED_WAITING    0                0:0              false            true             
63               as-command-execute-daemon                          system                            10               TIMED_WAITING    0                0:0              false            true             
43               job-timeout                                        system                            9                TIMED_WAITING    0                0:0              false            true             
1                main                                               main                              5                WAITING          0                0:0              false            false            
44               nioEventLoopGroup-2-1                              system                            10               RUNNABLE         0                0:0              false            false            
49               nioEventLoopGroup-2-2                              system                            10               RUNNABLE         0                0:0              false            false            
57               nioEventLoopGroup-2-3                              system                            10               RUNNABLE         0                0:0              false            false            
59               nioEventLoopGroup-2-4                              system                            10               RUNNABLE         0                0:0              false            false            
45               nioEventLoopGroup-3-1                              system                            10               RUNNABLE         0                0:0              false            false            
50               nioEventLoopGroup-3-2                              system                            10               RUNNABLE         0                0:0              false            false            
51               nioEventLoopGroup-3-3                              system                            10               RUNNABLE         0                0:0              false            false            
52               nioEventLoopGroup-3-4                              system                            10               RUNNABLE         0                0:0              false            false            
53               nioEventLoopGroup-3-5                              system                            10               RUNNABLE         0                0:0              false            false            
54               nioEventLoopGroup-3-6                              system                            10               RUNNABLE         0                0:0              false            false            
55               nioEventLoopGroup-3-7                              system                            10               RUNNABLE         0                0:0              false            false            
56               nioEventLoopGroup-3-8                              system                            10               RUNNABLE         0                0:0              false            false            
47               pool-2-thread-1                                    system                            5                WAITING          0                0:0              false            false            
                                                                                                                                                                                                            
## JVM内存使用情况
Memory                                      used          total          max           usage          GC    
heap                                        101M          323M           1820M         5.58%          gc.ps_scavenge.count                               8   
ps_eden_space                               65M           247M           648M          10.11%         gc.ps_scavenge.time(ms)                            199  
ps_survivor_space                           15M           15M            15M           99.92%         gc.ps_marksweep.count                              1    
ps_old_gen                                  20M           60M            1365M         1.50%          gc.ps_marksweep.time(ms)                           160 
nonheap                                     46M           47M            -1            98.30% 
code_cache                                  9M            9M             240M          4.07%   
metaspace                                   33M           33M            -1            98.29%  
compressed_class_space                      3M            4M             1024M         0.39% 
direct                                      66K           66K            -             100.00%                                                                  
mapped                                      0K            0K             -             NaN% 
                                                                                                              

##运行环境信息          
Runtime                                                                                                                                                         
os.name                                                                                               Mac OS X                                                  
os.version                                                                                            10.13.6                                                   
java.version                                                                                          1.8.0_171                                                 
java.home                                                                                /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre   
systemload.average                                                                                    2.07                                                      
processors                                                                                            4                                                         
uptime                                                                                                48084s                    

3.2 Thread

可以用来显示线程的一些基本信息,使用语法如下

 USAGE:
    thread [-b] [-i ] [--state ] [-n ] [id]  
   
 SUMMARY: 
    Display thread info, thread stack 
   
 EXAMPLES:
 thread
   thread 51
   thread -n -1
   thread -n 5
   thread -b
   thread -i 2000
   thread --state BLOCKED
   
 WIKI: 
   https://alibaba.github.io/arthas/thread                                                  
 OPTIONS:                                                                                                                                                                                                   
 -b, --include-blocking-thread                                       Find the thread who is holding a lock that blocks the most number of threads.                                                          
 -i, --sample-interval                                        Specify the sampling interval (in ms) when calculating cpu usage.                                                                      
     --state                                                  Display the thead filter by the state. NEW, RUNNABLE, TIMED_WAITING, WAITING, BLOCKED, TERMINATED is optional.                         
 -n, --top-n-threads                                          The number of thread(s) to show, ordered by cpu utilization, -1 to show all.                                                           
                                                                 Show thread stack 

例如使用 -n ,显示几条线程信息,根据cpu使用率排序

[arthas@7457]$ thread -n 3
"as-command-execute-daemon" Id=67 cpuUsage=82% RUNNABLE
    at sun.management.ThreadImpl.dumpThreads0(Native Method)
    at sun.management.ThreadImpl.getThreadInfo(ThreadImpl.java:448)
    at com.taobao.arthas.core.command.monitor200.ThreadCommand.processTopBusyThreads(ThreadCommand.java:179)
    at com.taobao.arthas.core.command.monitor200.ThreadCommand.process(ThreadCommand.java:100)
    at com.taobao.arthas.core.shell.command.impl.AnnotatedCommandImpl.process(AnnotatedCommandImpl.java:82)
    at com.taobao.arthas.core.shell.command.impl.AnnotatedCommandImpl.access$100(AnnotatedCommandImpl.java:18)
    at com.taobao.arthas.core.shell.command.impl.AnnotatedCommandImpl$ProcessHandler.handle(AnnotatedCommandImpl.java:111)
    at com.taobao.arthas.core.shell.command.impl.AnnotatedCommandImpl$ProcessHandler.handle(AnnotatedCommandImpl.java:108)
    at com.taobao.arthas.core.shell.system.impl.ProcessImpl$CommandProcessTask.run(ProcessImpl.java:371)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

    Number of locked synchronizers = 1
    - java.util.concurrent.ThreadPoolExecutor$Worker@ddde109


"SessionTracker" Id=12 cpuUsage=17% TIMED_WAITING on org.apache.zookeeper.server.SessionTrackerImpl@296b6b0a
    at java.lang.Object.wait(Native Method)
    -  waiting on org.apache.zookeeper.server.SessionTrackerImpl@296b6b0a
    at org.apache.zookeeper.server.SessionTrackerImpl.run(SessionTrackerImpl.java:147)


"Reference Handler" Id=2 cpuUsage=0% WAITING on java.lang.ref.Reference$Lock@24d69c83
    at java.lang.Object.wait(Native Method)
    -  waiting on java.lang.ref.Reference$Lock@24d69c83
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

查看一个非守护进程id,它正在AQS处等待。

[arthas@7457]$ thread 47
"pool-2-thread-1" Id=47 WAITING on java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@3f1125b4
    at sun.misc.Unsafe.park(Native Method)
    -  waiting on java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@3f1125b4
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Affect(row-cnt:0) cost in 32 ms.

3.3 jad

可以用来检查线上的发布代码是否是最新的。可以定位到具体类,或者具体方法。很方便.

[arthas@7457]$ jad javax.naming.NamingException initCause 

## 类加载器
ClassLoader:   
## 位置
Location:

## 对应的方法
@Override
public Throwable initCause(Throwable throwable) {
    super.initCause(throwable);
    this.setRootCause(throwable);
    return this;
}

Affect(row-cnt:1) cost in 167 ms.
[arthas@7457]$ 

3.4 mc redefine

编译类,并外部加载。

可以查看:https://alibaba.github.io/arthas/mc,https://alibaba.github.io/arthas/redefine

3.5 sc

查看jvm中加载的类的信息


[arthas@7457]$ help sc
 USAGE:
   sc [-c ] [-d] [-x ] [-f] [-h] [-E] class-pattern
   SUMMARY:
   Search all the classes loaded by JVM                                      
   
   EXAMPLES:                                                                                                                                                                                                  
   sc -d org.apache.commons.lang.StringUtils
   sc -d org/apache/commons/lang/StringUtils
   sc -d *StringUtils
   sc -d -f org.apache.commons.lang.StringUtils
   sc -E org\\.apache\\.commons\\.lang\\.StringUtils
   
 WIKI:
   https://alibaba.github.io/arthas/sc                                       
 OPTIONS:
 -c, --classloader                                            The hash code of the special class's classLoader
 -d, --details                                                       Display the details of class
 -x, --expand                                                 Expand level of object (0 by default)
 -f, --field                                                         Display all the member variables
 -h, --help                                                          this help
 -E, --regex                                                         Enable regular expression to match (wildcard matching by default)
                                                      Class name pattern, use either '.' or '/' as separator   

例如查看java.util.Stack类信息

[arthas@7457]$ sc -d java.util.Stack
 class-info        java.util.Stack
 code-source
 name              java.util.Stack
 isInterface       false
 isAnnotation      false
 isEnum            false
 isAnonymousClass  false
 isArray           false
 isLocalClass      false
 isMemberClass     false
 isPrimitive       false
 isSynthetic       false
 simple-name       Stack
 modifier          public
 annotation
 interfaces
 super-class       +-java.util.Vector
                     +-java.util.AbstractList
                       +-java.util.AbstractCollection
                         +-java.lang.Object
 class-loader
 classLoaderHash   null                                                      

Affect(row-cnt:1) cost in 20 ms.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

分割线,这里之后的测试,是自己写了一个简单测试类,方便看效果
放出类代码。各个命令的用法,请看 hepl 。注意以下的几个方法只是测试、排查时用。用完请reset/shutdown。还原被增强的字节码信息。
+++++++++++++++++++++++++++++++++++++++++++++++++++++++

package com.chl.arthes;

/**
 * 测试arthas的  sc,stack,track,monitor,watch等
 * @author chenhailong
 *
 */
public class TestArthas {

	public static void main(String[] args) {
		TestArthas ta = new TestArthas();
		for(int i = 0; i<1000; i++) {
			ta.first(ta);
			System.out.println("当前第"+i+"次");
		}
	}

	private void first(TestArthas ta) {
		try {
			Thread.sleep(1 * 1000l);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ta.second(ta);
	}
	
	private void second(TestArthas ta) {
		try {
			Thread.sleep(2 * 1000l);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ta.third(ta);
	}
	
	private void third(TestArthas ta) {
		try {
			Thread.sleep(3 * 1000l);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		four(1);
	}
	
	private static void four(int i) {
		try {
			Thread.sleep(4 * 1000l);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

3.6 stack

如下:指定不同方法,显示的调用栈信息不同。

## main方法
[arthas@10031]$ stack com.chl.arthes.TestArthas main 
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 62 ms.

## first方法
[arthas@10031]$ stack com.chl.arthes.TestArthas first 
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 14 ms.
ts=2020-04-08 14:15:21;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@4e25154f
    @com.chl.arthes.TestArthas.first()
        at com.chl.arthes.TestArthas.main(TestArthas.java:-1)

## four方法
[arthas@10031]$ stack com.chl.arthes.TestArthas four 
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 12 ms.
ts=2020-04-08 14:16:01;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@4e25154f
    @com.chl.arthes.TestArthas.four()
        at com.chl.arthes.TestArthas.third(TestArthas.java:42)
        at com.chl.arthes.TestArthas.second(TestArthas.java:33)
        at com.chl.arthes.TestArthas.first(TestArthas.java:24)
        at com.chl.arthes.TestArthas.main(TestArthas.java:-1)

3.7 Track

通过观察可以发现,只是检测出当前指定的方法内所调用的子方法执行时间,子方法的调用链条相关信息并没有。但是可以指定多个方法

[arthas@10031]$ trace com.chl.arthes.TestArthas second
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 15 ms.
`---ts=2020-04-08 14:21:32;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@4e25154f
    `---[9007.022122ms] com.chl.arthes.TestArthas:second()
        `---[7006.119983ms] com.chl.arthes.TestArthas:third() #33
        
## 指定多个方法
[arthas@10031]$ trace -E com.chl.arthes.TestArthas main|first|second|third|four
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:5) cost in 63 ms.
`---ts=2020-04-08 14:24:07;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@4e25154f
    `---[4002.333079ms] com.chl.arthes.TestArthas:four()

`---ts=2020-04-08 14:24:11;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@4e25154f
    `---[10012.039629ms] com.chl.arthes.TestArthas:first()
        `---[9009.76905ms] com.chl.arthes.TestArthas:second() #24
            `---[9009.523887ms] com.chl.arthes.TestArthas:second()
                `---[7006.258283ms] com.chl.arthes.TestArthas:third() #33
                    `---[7005.978271ms] com.chl.arthes.TestArthas:third()
                        `---[4001.466666ms] com.chl.arthes.TestArthas:four() #42
                            `---[4001.241582ms] com.chl.arthes.TestArthas:four()

3.8 watch

可以监控指定类、指定方法的参数|返回值|异常|方法等。可以用来查看一些环境的方法调用入参、出参信息等。也能排查部分特定类型的异常。

[arthas@10031]$ watch com.chl.arthes.TestArthas first params
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 18 ms.
ts=2020-04-08 14:27:12; [cost=10011.513947ms] result=@Object[][
    @TestArthas[com.chl.arthes.TestArthas@5197848c],
]
[arthas@10031]$ watch com.chl.arthes.TestArthas four params
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 17 ms.
ts=2020-04-08 14:27:32; [cost=4001.605734ms] result=@Object[][
    @Integer[1],
]

3.9 monitor

监控方法的使用情况(调用次数、执行时间、失败率等),也还挺有用的。

[arthas@10031]$ monitor com.chl.arthes.TestArthas first 
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 36 ms.
 timestamp            class                      method  total  success  fail  avg-rt(ms)  fail-rate                                                                                                        
-----------------------------------------------------------------------------------------------------                                                                                                       
 2020-04-08 14:34:25  com.chl.arthes.TestArthas  first   5      5        0     10008.78    0.00%                                                                                                            

 timestamp            class                      method  total  success  fail  avg-rt(ms)  fail-rate                                                                                                        
-----------------------------------------------------------------------------------------------------                                                                                                       
 2020-04-08 14:35:25  com.chl.arthes.TestArthas  first   6      6        0     10014.58    0.00%                                                                                                            

 timestamp            class                      method  total  success  fail  avg-rt(ms)  fail-rate                                                                                                        
-----------------------------------------------------------------------------------------------------                                                                                                       
 2020-04-08 14:36:25  com.chl.arthes.TestArthas  first   6      6        0     10013.24    0.00%

3.10 tt

记录方法调用信息,支持事后查看方法调用的参数,返回值,抛出的异常等信息,仿佛穿越时空隧道回到调用现场一般。感觉像moitor的展开版。记录每一次的调用情况。用处看情况而定吧。

[arthas@10031]$ tt -t com.chl.arthes.TestArthas first 
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 32 ms.
 INDEX        TIMESTAMP                      COST(ms)        IS-RET       IS-EXP      OBJECT                  CLASS                                           METHOD                                        
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 1000         2020-04-08 14:41:23            10012.799803    true         false       0x5197848c              TestArthas                                      first                                         
 1001         2020-04-08 14:41:33            10008.528389    true         false       0x5197848c              TestArthas                                      first                                         
 1002         2020-04-08 14:41:43            10008.465553    true         false       0x5197848c              TestArthas                                      first                                         
 1003         2020-04-08 14:41:53            10018.298319    true         false       0x5197848c              TestArthas                                      first                                         
 1004         2020-04-08 14:42:03            10018.851135    true         false       0x5197848c              TestArthas                                      first                                         
 1005         2020-04-08 14:42:13            10009.51691     true         false       0x5197848c              TestArthas                                      first                                         

4.0 火焰图

[arthas@10031]$ profiler start
Started [cpu] profiling

.... 等待一会后执行
[arthas@10031]$ profiler stop
profiler output file: /Users/chenhailong/eclipse-workspace2/MutilThreadTest/arthas-output/20200408-144819.svg
OK

生成的文件通过浏览器 http://127.0.0.1:8563/arthas-output/20200408-144819.svg 可访问。

火焰图,百度自己搜索吧。现在我还不清楚怎么看。

Arthas试用感受

挺好用的一工具,但是局限于现在试用的场景,但也还是能做很多分析的。以后在碰到实际问题的时候多多利用。熟能生巧,也是一个不错的助手。就到这里。

小尾巴:deathearth
官网:https://github.com/alibaba/arthas/blob/master/README_CN.md

你可能感兴趣的:(java基础)