This chapter explains how to investigate multithreaded Java applications by using profilers to observe thread behavior, lock contention, and waiting states. It starts from the idea that concurrency is powerful but difficult to implement correctly, especially when shared resources are protected by synchronization. By examining a simple producer-consumer program, the chapter shows how profiling can reveal whether threads are blocked, how often locking happens, and how long execution pauses last, giving developers practical visibility into what the JVM is doing during runtime.
Using the producer and consumer threads that share a single list, the chapter first demonstrates a classic locking scenario: both threads synchronize on the same monitor, so only one can modify the collection at a time. Profiling tools such as VisualVM and JProfiler make this visible through thread timelines, lock counts, and monitor histories. The key takeaway is that locks are not inherently bad, but they need to be understood and measured; in the example, the threads alternate fairly, and the measured behavior suggests the application is functioning as expected, with no obvious performance problem from the locking itself.
The chapter then contrasts locked threads with waiting threads by changing the example to use wait() and notifyAll(). Although this looks like a sensible improvement, profiling shows that the app becomes slower, with fewer lock events but much longer waiting time. This demonstrates an important lesson: moving from simple monitor contention to explicit waiting does not automatically improve performance, and sometimes it makes execution worse. The chapter closes by reinforcing that the only reliable way to judge multithreaded code is to profile it, compare CPU time with total execution time, and use the observed data to decide whether synchronization design is actually helping or hurting the application.
The app starts two threads that we refer to as “the producer” and “the consumer.” Both threads use a common resource: they change a list instance of type ArrayList. The producer generates random values and adds them to the list, while the consumer concurrently removes the values added by the producer.
Only one thread at a time can be in the synchronized block. Either the producer executes the logic defined in its run() method or the consumer executes its logic.
In most cases, the threads will sequentially lock each other and execute their synchronized blocks of code. The two threads can still concurrently execute the instructions, which are outside the synchronized block.
You can use other profilers instead of VisualVM. Here, you see the way thread timelines are displayed in JProfiler.
When the total CPU time is shorter than the total execution time, it means the app is waiting for something. We want to figure out what the app waits for and if this time can be optimized.
The method doesn’t wait for something, but instead it waits for itself. We observe that its self-execution time is longer than the total CPU time, which usually means that the thread is locked. The thread could have been blocked by another thread.
To start profiling for locks, use the Locks button in the Profiler tab. At the end of the profiling session, we observe more than 3,600 locks on each of our producer and consumer threads.
The profiling results give us a good understanding of what creates locks and what is affected by them. We see that there’s only one monitor the producer thread works with. Also, the producer thread was blocked by the consumer thread 3,698 times using the monitor. Using the same monitor instance, the producer blocked the consumer for a similar number of times: 3,699.
Both threads use the same monitor to block each other. While one thread executes the synchronized block with an ArrayList instance monitor, the other waits. This way, one thread is locked for 3,698 times and the other for 3,699.
When starting the profiling session with JProfiler, remember to set the JVM action to Keep the VM Alive for Profiling so that you can see the profiling results after the app finishes its execution.
JProfiler shows a detailed history of all the locks the app’s threads encountered. The tool displays the exact time of the event, the event duration, the monitor that caused the lock, and the threads that were involved.
You can group the lock events by threads involved or by monitors using the Monitor Usage Statistics section. You can use the aggregated view to understand which threads are more affected and what affects them or which monitor causes the threads to stop more often.
Grouping the lock events by threads provides you with an aggregated view showing how many times each of the threads locked during its execution.
Locked threads versus waiting threads. A locked thread is blocked at the entrance of a synchronized block. The monitor won’t allow a thread to enter a synchronized block while another thread actively runs inside the block. A waiting thread is a thread that the monitor has explicitly set to the blocked state. The monitor can make any thread inside the synchronized block it manages wait. The waiting thread can continue its execution only after the monitor explicitly tells it that it can proceed with its execution.
Some of the cars are consumer threads, and others are producer threads. The police officer orders a consumer to wait if the list doesn’t have values that can be consumed, allowing producers to work and add values. Once the list contains at least a value that can be consumed, the officer orders the waiting consumer to continue its execution.
By sampling the execution, we see that the execution time is slower than before we made threads wait.
By analyzing the details, we can see that the self execution time is not that long, but the thread is blocked and thus waits for a longer time.
The lock pattern is similar to our previous results, but the threads are locked less frequently.
We get the same details using JProfiler. Fewer threads are locked, but now they are blocked for a much longer time.
Summary
- A thread can be locked and forced to wait by a synchronized block of code. Locks appear when threads are synchronized to avoid changing shared resources at the same time.
- Locks are needed to avoid race conditions, but sometimes apps use faulty thread synchronization approaches, which can lead to undesired results such as performance issues or even app freezes (in the case of deadlocks).
- Locks caused by synchronized code blocks slow down the app’s execution because they force threads to wait instead of letting them work. Locks may be needed in certain implementations, but it’s better to find ways to minimize the time an app’s threads are locked.
- We can use a profiler to identify when locks slow down an app, how many locks the app encounters during execution, and how much they slow down performance.
- When using a profiler, always sample the execution first to figure out if the app’s execution is affected by locks. You’ll usually identify locks when sampling by observing that a method is waiting on itself.
- If you find by sampling that locks may be affecting the app’s execution, you can continue investigating using lock profiling (instrumentation), which will show the threads affected, the number of locks, the monitors involved, and the relationship between locked threads and threads that cause the locks. These details help you decide if the app’s execution is optimal or if you can find ways to enhance it.
- Each app has a different purpose, so there’s no unique formula for understanding thread locks. In general, we want to minimize the time threads are locked or waiting and make sure threads are not unfairly excluded from execution (starving threads).
FAQ
What is the main goal of investigating locks in a multithreaded Java application?
The main goal is to gain visibility into thread execution so you can identify where threads are blocked, what causes the blocking, and whether the synchronization strategy is hurting performance or causing freezes.
What is a thread lock in the context of this chapter?
A thread lock happens when a thread cannot continue execution because it is blocked by synchronization, such as entering a synchronized block, waiting for another thread to finish, or being controlled by a blocking object.
Why do the producer and consumer threads in the example block each other?
Both threads use the same ArrayList instance as a monitor. Since each thread synchronizes on that shared list, only one can enter the critical section at a time, forcing the other to wait.
How can a profiler help identify lock-related problems?
A profiler can show which threads were blocked, how often they were blocked, how long they waited, and which monitor object caused the blocking. This makes it easier to understand contention patterns and possible optimization points.
Why does the chapter recommend starting with sampling before deeper profiling?
Sampling gives a high-level view of execution and helps detect suspicious behavior, such as total execution time being much longer than CPU time. After that, instrumentation can be used to investigate the specific cause in detail.
What does it mean when a method seems to be “waiting on itself” in the profiler?
It usually means the thread is not actually waiting on external work; instead, it is likely blocked or locked by another thread. The profiler may show long self-execution time compared to CPU time, which is a clue that the thread is being contended.
How do you interpret the lock statistics for the producer and consumer threads?
The statistics show how many times each thread was blocked and which thread caused the blocking. In the example, each thread blocks the other roughly the same number of times, indicating mutual exclusion on the shared monitor.
What does the monitor object reference in the profiler tell you?
The object reference uniquely identifies the shared monitor instance, allowing you to confirm that the same object is responsible for blocking multiple threads and to trace the exact relationship between threads and the lock.
Why did adding wait() and notifyAll() make the example slower?
Because it shifted the waiting from lock contention to explicit waiting, resulting in fewer lock events but much longer waiting times. In this case, the wait/notify approach increased overall execution time rather than improving it.
When should you consider changing a multithreaded design to reduce lock contention?
You should consider it when profiling shows excessive waiting, uneven thread access, starvation risk, or poor overall execution time. Possible improvements include reducing lock scope, batching work, or redesigning how threads coordinate shared resources.