Mastering Multithreading in Java

Multithreading is one of Java's most powerful features, enabling applications to perform multiple tasks concurrently and maximize CPU utilization. In this comprehensive guide, we'll explore how threads work in Java, the different ways to create them, and critical concepts like synchronization and thread management.

What is a Thread?

A thread represents a single flow of control within a program. While your application runs as a process, threads allow multiple sequences of execution to run concurrently within that process, sharing the same memory space but executing independently.

Java provides robust built-in support for multithreading, making it straightforward to create responsive applications that can handle multiple operations simultaneously.

Creating Threads in Java

Java offers two primary approaches to create threads:

1. Implementing the Runnable Interface

The Runnable interface is the recommended approach for creating threads. It provides a clean separation between the task logic and the thread execution mechanism.

Key characteristics:

  • Contains a single method: run()
  • The run() method defines the code that executes in the new thread
  • More flexible since your class can extend another class while implementing Runnable

Example:

class MyTask implements Runnable {
    public void run() {
        System.out.println("Thread executing: " + Thread.currentThread().getName());
        // Your task logic here
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyTask task = new MyTask();
        Thread thread = new Thread(task);
        thread.start();
        
        // You can also name your thread
        Thread namedThread = new Thread(task, "WorkerThread");
        namedThread.start();
    }
}

How it works:

  1. Create a class that implements Runnable
  2. Implement the run() method with your task logic
  3. Create a Thread object, passing your Runnable implementation
  4. Call start() to begin execution

The start() method is crucial here. It changes the thread's state to Runnable and signals the JVM to call the run() method in a new execution context. Never call run() directly, as this would execute the code in the current thread rather than creating a new one.

2. Extending the Thread Class

The second approach involves creating a subclass of Thread and overriding its run() method.

Example:

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread executing: " + getName());
        // Your task logic here
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

When to use each approach:

  • Use Runnable when you need to extend another class or want better separation of concerns
  • Use Thread extension when you need to override additional Thread methods or when simplicity is preferred

Essential Thread Methods

The Thread class provides several important methods for thread management:

Basic Thread Control

getName() / setName(String name)

  • Retrieve or set the thread's name for identification and debugging

getPriority() / setPriority(int priority)

  • Get or set thread priority (range: Thread.MIN_PRIORITY to Thread.MAX_PRIORITY, typically 1-10, default is 5)
  • Higher priority threads are given preference by the scheduler, though behavior is platform-dependent

isAlive()

  • Returns true if the thread has been started and hasn't yet terminated
  • Useful for checking thread status

currentThread()

  • Static method that returns a reference to the currently executing thread
  • Commonly used: Thread.currentThread().getName()

Thread Coordination Methods

sleep(long milliseconds)

  • Pauses the current thread's execution for the specified duration
  • Thread remains in a blocked state and doesn't consume CPU cycles
  • Always handle InterruptedException
try {
    Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
    e.printStackTrace();
}

yield()

  • Hints to the scheduler that the current thread is willing to yield its processor time
  • The scheduler may choose to ignore this hint
  • Useful for preventing thread starvation in compute-intensive loops

join()

  • Waits for a thread to complete before continuing execution
  • Essential for coordinating dependent tasks
Thread worker = new Thread(task);
worker.start();
worker.join(); // Main thread waits here until worker completes
System.out.println("Worker has finished");

Managing the Main Thread

A common requirement is ensuring that the main thread doesn't exit before child threads complete their work. There are two primary approaches:

Using join()

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(new MyTask());
        worker.start();
        worker.join(); // Wait for worker to complete
        System.out.println("All threads completed");
    }
}

Using isAlive()

public class ThreadDemo {
    public static void main(String[] args) {
        Thread worker = new Thread(new MyTask());
        worker.start();
        
        while (worker.isAlive()) {
            // Main thread waits
        }
        System.out.println("All threads completed");
    }
}

The join() method is generally preferred as it's cleaner and more efficient than busy-waiting with isAlive().

Thread Priorities

Java allows you to influence thread scheduling through priorities:

Thread highPriorityThread = new Thread(task);
highPriorityThread.setPriority(Thread.MAX_PRIORITY); // 10

Thread lowPriorityThread = new Thread(task);
lowPriorityThread.setPriority(Thread.MIN_PRIORITY); // 1

Thread normalThread = new Thread(task);
// Default priority is Thread.NORM_PRIORITY (5)

Important notes:

  • Thread priorities are hints to the scheduler, not guarantees
  • Actual behavior varies across different operating systems and JVM implementations
  • Don't rely solely on priorities for correctness; use proper synchronization instead

Synchronization: Thread-Safe Programming

When multiple threads access shared resources, synchronization becomes critical to prevent race conditions and data corruption.

Synchronized Methods

The synchronized keyword ensures that only one thread can execute a method on a given object instance at a time.

public class Counter {
    private int count = 0;
    
    public synchronized void increment() {
        count++;
    }
    
    public synchronized int getCount() {
        return count;
    }
}

How it works:

  • When a thread enters a synchronized method, it acquires the object's intrinsic lock (monitor)
  • Other threads attempting to call any synchronized method on the same instance must wait
  • The lock is released when the method completes

Synchronized Blocks

When you can't modify the original class or need finer-grained control, use synchronized blocks:

public class ThreadSafeProcessor {
    private final Object lock = new Object();
    
    public void process(SomeObject obj) {
        // Non-synchronized code here
        
        synchronized(obj) {
            // Only this critical section is synchronized
            obj.criticalMethod();
        }
        
        // More non-synchronized code
    }
}

Synchronized blocks offer several advantages:

  • Lock only the critical section, improving performance
  • Synchronize on different objects for different resources
  • Use when working with legacy or third-party code

Static Synchronized Methods

Static synchronized methods lock at the class level rather than the instance level:

public class SharedResource {
    private static int sharedCounter = 0;
    
    // Locks on the Class object
    public static synchronized void incrementShared() {
        sharedCounter++;
    }
    
    // Locks on the instance
    public synchronized void incrementInstance() {
        // instance-specific code
    }
}

This distinction is important: static synchronized methods have a single lock shared across all instances, while non-static synchronized methods have one lock per instance.

Deprecated Thread Methods: What to Avoid

Several Thread methods have been deprecated due to safety concerns:

suspend() and resume()

Why deprecated: Suspending a thread while it holds locks can cause deadlocks. Other threads waiting for those locks would be blocked indefinitely.

stop()

Why deprecated: Forcibly stopping a thread can leave objects in an inconsistent state. Once stopped, a thread cannot be restarted.

Better alternatives:

  • Use a flag to signal threads to terminate gracefully
  • Use interrupt() for cooperative cancellation
class SafeThread extends Thread {
    private volatile boolean running = true;
    
    public void run() {
        while (running) {
            // Do work
        }
        // Clean up resources
    }
    
    public void shutdown() {
        running = false;
    }
}

wait() and notify()

For advanced thread coordination, use wait() and notify() instead of suspend/resume:

public class ProducerConsumer {
    private final Object lock = new Object();
    private boolean dataReady = false;
    
    public void produce() {
        synchronized(lock) {
            // Produce data
            dataReady = true;
            lock.notify(); // Wake up waiting consumer
        }
    }
    
    public void consume() throws InterruptedException {
        synchronized(lock) {
            while (!dataReady) {
                lock.wait(); // Release lock and wait
            }
            // Consume data
            dataReady = false;
        }
    }
}

Best Practices and Common Pitfalls

1. Always Use start(), Never Call run() Directly

// Wrong - executes in current thread
thread.run();

// Correct - creates new thread
thread.start();

2. Handle InterruptedException Properly

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // Restore interrupt status
    Thread.currentThread().interrupt();
    // Handle appropriately
}

3. Minimize Synchronized Scope

// Bad - entire method synchronized
public synchronized void process() {
    nonCriticalOperation1();
    criticalOperation();
    nonCriticalOperation2();
}

// Better - only critical section synchronized
public void process() {
    nonCriticalOperation1();
    synchronized(this) {
        criticalOperation();
    }
    nonCriticalOperation2();
}

4. Avoid Deadlocks

Always acquire locks in a consistent order across your application:

// Thread 1
synchronized(lockA) {
    synchronized(lockB) {
        // Work
    }
}

// Thread 2 - same order prevents deadlock
synchronized(lockA) {
    synchronized(lockB) {
        // Work
    }
}

Conclusion

Multithreading in Java is a powerful tool for building responsive, efficient applications. By understanding the fundamentals of thread creation, lifecycle management, and synchronization, you can harness concurrency while avoiding common pitfalls.

Key takeaways:

  • Prefer implementing Runnable over extending Thread for flexibility
  • Use join() and isAlive() to coordinate thread completion
  • Apply synchronization to protect shared resources from race conditions
  • Avoid deprecated methods like suspend(), resume(), and stop()
  • Follow best practices to write thread-safe, maintainable code

As you advance, explore higher-level concurrency utilities in the java.util.concurrent package, which provide more sophisticated tools for parallel programming while abstracting many low-level threading details.

Happy threading!

Comments

Popular posts from this blog

Creational Design Pattern: Factory Design Pattern

Introduction to Java

Design Patterns: The Secret Weapon of Expert Developers