Introduction

Java synchronized blocks deadlock when multiple threads acquire locks in different order. This guide provides step-by-step diagnosis and resolution with specific commands and code examples.

Symptoms

Typical symptoms and error messages when this issue occurs:

bash
java.lang.Error: Unexpected error occurred
	at com.example.Application.main(Application.java:42)
Caused by: internal error

Observable indicators: - Application logs show errors or exceptions - JVM crashes or becomes unresponsive - Related services may fail or timeout

Common Causes

  1. 1.Deadlock and hang issues are caused by:
  2. 2.Circular dependencies in lock acquisition
  3. 3.Missing timeout in wait operations
  4. 4.Incorrect thread synchronization
  5. 5.Resource starvation

Step-by-Step Fix

Step 1: Check Current State

bash
java -version

Step 2: Identify Root Cause

bash
jcmd <pid> VM.info

Step 3: Apply Primary Fix

```java // Use timeout with locks to avoid deadlock Lock lock1 = new ReentrantLock(); Lock lock2 = new ReentrantLock();

try { if (lock1.tryLock(100, TimeUnit.MILLISECONDS)) { try { if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) { try { // Critical section } finally { lock2.unlock(); } } } finally { lock1.unlock(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ```

Apply this configuration and restart the application.

Step 4: Apply Alternative Fix (If Needed)

```java // Use ordered lock acquisition public class DeadlockPrevention { private static final Object lock1 = new Object(); private static final Object lock2 = new Object();

public void method1() { synchronized (lock1) { synchronized (lock2) { // Always acquire in same order } } }

public void method2() { synchronized (lock1) { // Same order as method1 synchronized (lock2) { // Prevents deadlock } } } } ```

Test the fix under normal and peak load conditions to verify stability.

Step 5: Verify the Fix

After applying the fix, verify with:

bash
java -jar application.jar --debug

Expected output should show successful operation without errors.

Common Pitfalls

  • Not reading error messages carefully
  • Applying fixes without understanding root cause
  • Skipping verification after changes

Best Practices

  • Read official documentation first
  • Test in isolated environment
  • Document changes for team visibility
  • Java OutOfMemoryError
  • Java StackOverflowError
  • Java ClassNotFoundException