Tuning Process
Prerequisites
- The server and OS are running properly.
- An SSH remote login tool has been installed on the local PC.
- The Java program to be tuned is running on the target server.
Procedure
Obtain the required demo from testdemo.
- Perform profiling analysis.
On the Overview tab page, check the number of threads in each state.
Figure 1 Overview 1
It is found that a large number of threads are blocked, which may cause lock contention.
- View the thread list on the CPU tab page and perform the thread dump operation for multiple times.Figure 2 Thread Dump
- View the Thread Dump tab page.Figure 3 Thread Dump - Thread Overview
Use the Status field to display blocked threads, and click Monitor Details to view the lock information.
Figure 4 Thread Dump
- View the monitor details on the Thread Dump tab page.It is found that the 0x0000000101c98088 lock has been held and 50 threads are contending for the lock at the same time.Figure 5 Monitor Details
Locate the specific code for analysis based on the stack information on the Thread Overview page.
Figure 6 Thread Overview
It is found that the program is using the synchronized lock instead of a j.u.c.Lock. If the lock contention is fierce, the lock is upgraded to a heavyweight lock. As a result, context switches become frequent, affecting the performance and blocking key services.
- Analyze the causes.
Based on the types and locations of the locks provided in Thread Dump, we can analyze the service logic of the code to find a tuning solution. The following describes two tuning methods for lock contention, which are for reference only.
- Scenario 1: The synchronized keyword is used, but the contention in services is fierce.
Replace synchronized with a j.u.c.Lock (such as ReentrantLock).
- Scenario 2: A j.u.c.Lock is used, but the contention in services is fierce.
In this case, you need to add other policies to improve the system performance. For example, add a thread pool to limit the number of threads that compete for the lock. In the read/write splitting scenario, you can use ReadWriteLock.
- Scenario 1: The synchronized keyword is used, but the contention in services is fierce.
Summary
Once a lock contention problem occurs in Java, it is difficult to locate the specific code because there are many program interference factors. However, the problem can be located based on thread dump. The stack information provides the code location where the lock contention occurs.
If multiple threads attempt to lock the same lock address, the program is experiencing lock contention. When tuning other programs, you need to perform tuning operations based on the analysis results collected by the Java Profiler and the corresponding tuning suggestions. For details about the tuning roadmap, see this practice.