Multithreading in Java
Multithreading in Java allows a program to perform multiple tasks at the same time by running several threads concurrently within a single process. Each th...
What Is Multithreading?
Multithreading in Java allows a program to perform multiple tasks at the same time by running several threads concurrently within a single process. Each thread is an independent path of execution that shares the same memory space as other threads in the same application. This makes multithreading fundamentally different from multiprocessing, where separate memory spaces are used.
Java has built-in support for multithreading at the language level, which means you do not need external libraries to create or manage threads. The Java Virtual Machine schedules threads onto available CPU cores, giving your program the ability to make better use of modern hardware. For instance, a web server written in Java can handle dozens of client requests simultaneously, each on its own thread, instead of waiting for one request to finish before starting the next.
The main benefit of multithreading is improved throughput and responsiveness. A long-running background task, such as reading a file or querying a database, can run on a separate thread while the main thread continues responding to user input. This pattern is common in Android applications, desktop GUIs, and server-side Java programs.
Here is a simple example of creating and starting a thread by extending the Thread class:
class Counter extends Thread { public void run() { for (int i = 1; i <= 5; i++) System.out.println(i); } } Counter c = new Counter(); c.start();
Multithreading does introduce complexity. Shared data can be corrupted if two threads modify it at the same time, which is called a race condition. Developers must use synchronization techniques to prevent this. Understanding these trade-offs is essential before writing concurrent Java programs.
Interview tip: Be ready to explain the difference between parallelism and concurrency. Parallelism means tasks literally run at the same moment on multiple cores; concurrency means tasks make progress over overlapping time periods, even on a single core through context switching.
Thread Priority and Scheduling
Every Java thread has a priority that hints to the JVM scheduler how to order thread execution. Priorities range from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10), with Thread.NORM_PRIORITY (5) as the default. Setting a higher priority does not guarantee a thread will run first; the actual scheduling behavior depends on the underlying operating system.
The JVM uses a preemptive, priority-based scheduling model. When a higher-priority thread becomes runnable, the scheduler may preempt a lower-priority thread to give CPU time to the more important one. However, because different operating systems implement thread scheduling differently, relying on priority alone for correctness is a bad practice. Priority should be used only as a performance hint, never as a synchronization mechanism.
You can set a thread's priority before calling start() using the setPriority() method. For example:
Thread t = new Thread(() -> System.out.println("Running")); t.setPriority(Thread.MAX_PRIORITY); t.start();
Java also supports daemon threads, which are background threads that terminate automatically when all non-daemon threads in the program have finished. Garbage collection runs on a daemon thread. You mark a thread as a daemon by calling setDaemon(true) before starting it. If the JVM exits because only daemon threads remain, those threads are killed without finishing their run() method.
Thread starvation can occur when low-priority threads never get CPU time because high-priority threads monopolize the processor. This is more common on Windows systems. To avoid starvation, prefer using the concurrency utilities in the java.util.concurrent package, which provide fairer scheduling mechanisms compared to raw thread priority manipulation.
Interview tip: When asked about thread priority, mention that it is not reliable across platforms and that you prefer using ExecutorService for managing thread pools rather than manipulating priorities directly.
Common Multithreading Problems
Writing multithreaded Java code introduces a class of bugs that do not appear in single-threaded programs. The three most important problems to understand are race conditions, deadlocks, and thread starvation. Each requires a different prevention strategy, and recognizing which problem you are facing is the first step toward a solution.
A race condition happens when two threads read and write a shared variable without coordination, producing results that depend on the unpredictable timing of thread execution. For example, if two threads each read a counter value of 5, both increment it, and both write back 6, the counter ends up at 6 instead of the correct 7. Using the synchronized keyword or atomic classes from java.util.concurrent.atomic prevents this.
A deadlock occurs when two or more threads each hold a lock that the other threads need, so none of them can proceed. Imagine Thread A holds Lock 1 and waits for Lock 2, while Thread B holds Lock 2 and waits for Lock 1. Both threads wait forever. Preventing deadlocks requires always acquiring locks in a consistent global order across all threads.
Thread starvation is a situation where a thread is perpetually denied access to a resource it needs because other threads continuously take priority. This can happen with synchronized blocks if some threads are more aggressive about acquiring the lock. Using fair locks, available through ReentrantLock with the fairness flag set to true, can help distribute access more evenly.
Example of a basic race condition fix using synchronized:
private int count = 0; public synchronized void increment() { count++; }
Livelock is a related problem where threads actively respond to each other but make no real progress, similar to two people in a hallway who keep stepping aside in the same direction.
Interview tip: Always mention deadlock prevention strategies when discussing synchronization. Explain that consistent lock ordering, using tryLock with timeouts, and preferring higher-level concurrency abstractions are the three main defenses against deadlocks.