SoFunction
Updated on 2025-03-04

The role and usage of Arthas in java

1. Introduction to Arthas

The Origin and Background of Arthas

Arthas is an open source Java diagnostic tool by Alibaba. Its main design is to help developers quickly locate problems and solve various Java applications without restarting applications in the production environment. Arthas' name comes from a character in World of Warcraft, symbolizing its power and authority in the field of Java application diagnostics. This tool is especially suitable for dealing with complex production environment problems, such as performance bottlenecks, memory leaks, exception analysis, etc.

The main functions and features of Arthas

Feature Overview:

  1. Real-time monitoring:Arthas can monitor various operating indicators of the JVM in real time, including but not limited to CPU utilization, memory usage, thread status, etc.
  2. View class information:You can view the information of the class loaded in the JVM, including the class loader, class metadata, loading location, etc.
  3. Dynamic tracking:Arthas allows users to dynamically track method calls and method execution times, which is very helpful in diagnosing performance issues.
  4. Conditional expression breakpoint:Users can set conditional expressions, and when the condition is satisfied, Arthas will pause application execution, which is similar to the debugger's breakpoint function.
  5. JVM and system diagnostics:Provides commands to view and diagnose JVM and system-level detailed information, such as system properties, environment variables, thread stacks, etc.
  6. Command extensions and script execution:Supports users to write custom commands or scripts to suit specific monitoring or diagnostic needs.

Feature summary:

  • Non-invasive design:Monitoring and diagnosis is possible without modifying the application's code.
  • Security:Arthas is designed with security in mind to ensure the safe use of tools in production environments.
  • Ease of use:Provides rich commands and a friendly command line interface that can be quickly started for beginners.
  • High scalability:The open source features make Arthas highly customizable and extensible, active community, and continuous iterative updates.

2. Installation and startup of Arthas

Environmental requirements before installation

Before installing Arthas, you need to make sure your system meets the following environmental requirements:

  • operating system: Supports mainstream operating systems such as Linux/Mac OS/Windows.
  • Java version: Supports Java 6 and above. Java 8 or higher is recommended for best performance and compatibility.
  • Permissions: Ensure that you have sufficient permissions to access the running Java process.

Download and install Arthas

Arthas can be installed in a number of ways, and here are some of the common methods:

1. Install through official scripts

Using the installation script provided by Arthas is the fastest way to install it.

Enter the following command in the command line to install:

curl -L / | sh

This command will automatically download the latest version of Arthas and decompress it to the current user's home directory.arthasFolder.

2. Manually download the installation package

You can alsoGitHub releases pageDownload the latest Arthas zip package and manually unzip it to the specified directory.

After decompression, enter the Arthas directory and you can see(Linux/Mac) or(Windows) script file to start Arthas.

Start Arthas

The steps to start Arthas are as follows:

1. Open the command line tool

Open the command line tool according to your operating system.

2.Locate to the Arthas directory

usecdCommand to enter containsorArthas directory.

3. Execute the startup script

On Linux or Mac, run the following command:

./

On Windows, run the following command:

4. Select Java process

After starting the script, Arthas will list the currently running Java process. Enter the Java process ID to diagnose as prompted.

5. Enter the Arthas command line interface

After selecting a process, Arthas will start and enter its command line interface, and you can start using various commands to diagnose and monitor Java applications.

3. Introduction to common functions

Arthas provides a series of powerful functions to help developers diagnose and solve problems with running Java applications.

Here are some detailed introductions to some commonly used functions:

Real-time monitoring of JVM status

Arthas allows users to monitor the JVM's key performance metrics in real time, which is essential to maintaining the healthy operation of applications.

By usingdashboardCommands, developers can view the CPU usage, memory usage, GC status, and thread status of the JVM in real time.

This command provides a dynamically refreshed dashboard that shows the overall health of the current JVM.

Example of usage

$ dashboard

Dynamic tracking Java method execution

Arthas'straceThe command allows the developer to track the method-level call process and displays the time-consuming and call paths of each method call. This is very useful for positioning performance bottlenecks and complex error call flows.

Example of usage

$ trace  yourMethod

This command will trackYourClassmiddleyourMethodThe execution of the method, including all the sub-methods it calls.

View real-time information about the JVM and system

Arthas'sthreadandjvmCommands can be used to view system and JVM details.

  • threadThe command provides snapshots of all threads in the current JVM to help developers analyze thread status and problems.
  • andjvmThe command displays more comprehensive JVM-related information, such as memory information, GC information, and JVM configuration parameters.

Example of usage

  • View thread information:
$ thread
  • View JVM information:
$ jvm

Through these features, Arthas helps developers monitor and diagnose the status of Java applications in real time without stopping the application, thereby quickly responding to and solving problems in production environments.

4. Use cases

Arthas is a powerful Java diagnostic tool that can help developers diagnose and solve problems in a variety of scenarios. Here are some specific use cases showing how to use Arthas to solve common Java application problems.

Use Arthas to diagnose slow application startup issues

Problem scenario: The application startup is extremely slow and requires the diagnosis of bottlenecks during startup.

Solution steps

1. Start Arthas: The process connected to the application.

2. UsetraceKey methods for command tracking: Can be usedtraceCommand tracks key methods involved in the application startup process, such as the initialization method of the Spring framework.

The command is as follows:

trace  preInstantiateSingletons

This will show the time and call path of the method execution, helping to identify time-consuming methods.

3. Analyze the output results: Identify methods that have been called for too long and further analyze specific reasons, such as configuration problems, resource competition, etc.

Use Arthas to resolve memory leaks

Problem scenario: A memory leak occurred after the application was running for a period of time.

Solution steps

Start Arthas and connect to the target process

useheapdumpCommand to export heap memory: The command is as follows:

heapdump

This will generate a snapshot of heap memory that can be further analyzed using memory analysis tools such as MAT.

Analyze heap memory files: Use memory analysis tools to find large objects, long-term survival objects and their reference chains to locate the source of memory leaks.

Optimize performance bottlenecks with Arthas

Problem scenario: During the application run, some operations respond to too long.

Solution steps

usedashboardCommand to monitor system status: Check the system's real-time health status, including threads and CPU usage.

usewatchCommands to monitor the execution of specific methods

watch  myMethod "{params, returnObj, throwExp}"

By monitoring the input parameters, return values ​​and exceptions of the method, you can observe the running status of the method in real time.

useprofilerCommands for performance analysis

profiler start

After running for a period of time, useprofiler stopEnd the analysis and generate a performance report to identify performance bottlenecks through the analysis report.

Through these specific cases, we can see how Arthas plays its powerful functions in different scenarios. These tools not only help developers diagnose problems, but also optimize application performance and improve development and maintenance efficiency.

5. Advanced features of Arthas

Arthas not only provides basic diagnostic tools, but also includes some advanced features, allowing developers to more flexible and in-depth problem analysis and performance optimization.

Here are some advanced features.

Use of conditional expressions

Arthas supports the use of conditional expressions when executing commands, which allows developers to more precisely control the execution conditions of commands.

For example, in usewatchWhen monitoring methods, you can filter calls that are triggered only under specific conditions through conditional expressions.

Example of usage

$ watch  yourMethod "{params, returnObj}" "params[0]>100"

This command monitoringYourClassofyourMethodMethod, the parameters and return values ​​will be printed only when the first parameter is greater than 100.

Asynchronous commands and batch commands

Arthas allows command execution in an asynchronous manner, which is especially useful for monitoring or analysis that requires long-running.

AvailableasyncCommand to start asynchronous tasks, usejobsView the currently running task and usekillTerminate the task.

Example of usage

$ async trace  yourMethod
$ jobs  // View the current task$ kill 1  // Termination number is1Mission

In addition, Arthas supports batch commands, which can write multiple commands into a script file and then pass--batchParameters are executed at one time.

Example of usage

$ arthas-boot --batch 

inIt is a script file containing multiple Arthas commands.

Custom monitoring view

Arthas allows users to customize monitoring views, which is combined withdashboardwatchandtraceWait for the command to be implemented.

Users can customize output formats according to their needs, and even integrate multiple data sources to create complex monitoring views.

Example of usage

$ dashboard --view thread,gc,memory,cpu,sys

This command customizes a dashboard and monitors threads, GC, memory, CPU and system information at the same time.

Through these advanced features, Arthas provides great flexibility and powerful capabilities, making diagnostic and performance optimization of Java applications more efficient and in-depth.

5. Advanced features of Arthas

Arthas not only provides basic diagnostic tools, but also includes some advanced features, allowing developers to more flexible and in-depth problem analysis and performance optimization. Here are some advanced features.

Use of conditional expressions

Arthas supports the use of conditional expressions when executing commands, which allows developers to more precisely control the execution conditions of commands.

For example, in usewatchWhen monitoring methods, you can filter calls that are triggered only under specific conditions through conditional expressions.

Example of usage

$ watch  yourMethod "{params, returnObj}" "params[0]>100"

This command monitoringYourClassofyourMethodMethod, the parameters and return values ​​will be printed only when the first parameter is greater than 100.

Asynchronous commands and batch commands

Arthas allows command execution in an asynchronous manner, which is especially useful for monitoring or analysis that requires long-running. AvailableasyncCommand to start asynchronous tasks, usejobsView the currently running task and usekillTerminate the task.

Example of usage

$ async trace  yourMethod
$ jobs  // View the current task$ kill 1  // Termination number is1Mission

In addition, Arthas supports batch commands, which can write multiple commands into a script file and then pass--batchParameters are executed at one time.

Example of usage

$ arthas-boot --batch 

inIt is a script file containing multiple Arthas commands.

Custom monitoring view

Arthas allows users to customize monitoring views, which is combined withdashboardwatchandtraceWait for the command to be implemented. Users can customize output formats according to their needs, and even integrate multiple data sources to create complex monitoring views.

Example of usage

$ dashboard --view thread,gc,memory,cpu,sys

This command customizes a dashboard and monitors threads, GC, memory, CPU and system information at the same time.

Through these advanced features, Arthas provides great flexibility and powerful capabilities, making diagnostic and performance optimization of Java applications more efficient and in-depth.

6. Frequently Asked Questions and Solutions

Users may encounter some common problems when using Arthas for application diagnostics. Here are solutions to these problems to help users use Arthas more effectively.

Arthas command does not respond

Problem description: After executing the Arthas command, there is no output and the command seems to be suspended.

Possible causes and solutions

  1. The target process is too high: Check the CPU and memory usage of the target Java process to confirm whether the command execution is slow due to system resources shortage.
  2. Command execution conditions are not met: If a conditional expression is used, confirm whether the condition is set correctly or too strict.
  3. Network issues: If you connect to the target process (such as remote diagnosis) through the network, check whether the network connection is stable.
  4. Restart Arthas: Sometimes restarting the Arthas client can solve the problem of unresponsive commands.

Compatibility issues dealing with

Problem description: Arthas does not run properly on certain Java versions or operating systems.

Possible causes and solutions

  1. Java version differences: Make sure Arthas supports the Java version you are using. Arthas usually supports Java 6 and above, but it is best to check the latest official documentation to confirm compatibility information.
  2. Operating system specific problems: Some operating systems may require specific configuration to run Arthas. For example, on Windows systems, you may need to run command line tools with administrator privileges.
  3. Update Arthas: Use the latest version of Arthas to take advantage of the latest features and compatibility improvements.

Performance Impact Assessment

Problem description: Worrying that using Arthas in production environment will affect application performance.

Assessment and mitigation measures

  1. Command selection: Avoid using commands that have a significant impact on performance during peak hours, such astracemonitorwait.
  2. Using sampling analysis:useprofilerWhen performing performance analysis, you can select the sampling mode, which has a less impact on performance.
  3. Limit output: Reduce the impact on application performance by limiting the amount of data output by the command. For example, it can be restrictedwatchThe number or size of the result output by the command.
  4. Monitoring performance indicators: When using Arthas, continuously monitor key performance indicators such as CPU, memory and response time to promptly detect and deal with possible performance problems.

7. Best practices for practical development

Arthas is a powerful Java diagnostic tool, and using it rationally can greatly improve development and operation and maintenance efficiency. Here are the best practices for using Arthas in development and production environments.

Using Arthas in a development environment

Problem location and resolution

  • In a development environment, using Arthas can help developers quickly locate problems, such as performance bottlenecks, exception throwing points, deadlock problems, etc.
  • passtrace, watchandmonitorDevelopers can observe method calls and runtime data in real time.

Code optimization

  • Leverage Arthas' real-time monitoring and analysis capabilities
  • Developers can evaluate the impact of code changes on performance
  • Thus, optimize code implementation

Learning and experimenting

  • Arthas' security and ease of use make it an ideal learning tool
  • Developers can gain insight into Java bytecode execution, JVM performance characteristics, etc. through Arthas

Integration Testing

  • During automated testing
  • Arthas can be integrated to monitor application performance and abnormal behavior
  • Make sure that code changes do not introduce new performance issues

Use Arthas with caution in production environments

Minimize performance impact

  • When using Arthas in a production environment, the impact on application performance should be minimized.
  • For example, usetraceandwatchDuring commands, the monitoring range and frequency should be limited to avoid the generation of large amounts of log data.

Safety considerations

  • Ensure that the access to Arthas is strictly controlled and avoid unauthorized access.
  • Access to the Arthas ports can be restricted through network policies and security groups.

Emergency response

  • In production environments, Arthas can be used as an emergency response tool to quickly locate emergencies.
  • Therefore, it is recommended to prepare the usage strategies and operational processes of Arthas in advance to quickly start and use when needed.

Logging and auditing

  • When using Arthas for problem diagnosis, relevant operations and results should be recorded as the basis for post-event analysis and audit.

Regular evaluation and testing

  • Test and evaluate the use of Arthas regularly in non-production environments
  • Ensure that use in production environments does not cause unexpected problems

8. Resources and further learning

To gain a deeper understanding and effective use of Arthas, here are some official resources and community platforms that can help users from getting started to mastering.

Official documentation and tutorials

Arthas official GitHub page

  • accessArthas GitHubThe page provides the latest release information, source code and detailed development documentation.
  • The GitHub page also contains installation guides, quick start guides, and detailed feature descriptions.

Arthas official website

  • Arthas' official website Comprehensive documentation is provided, including installation, command reference, advanced features, and FAQ.
  • There are also video tutorials and case analysis on the website to help users learn how to use Arthas through practical examples.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.