Runnable Interface in Java
The Runnable interface is the preferred way to define a task for a thread in Java. It contains a single method: public void run(). When you implement Runna...
Implementing Runnable
The Runnable interface is the preferred way to define a task for a thread in Java. It contains a single method: public void run(). When you implement Runnable instead of extending Thread, you separate the task logic from the thread machinery. This gives you more flexibility because your class can still extend another class, and the same Runnable instance can be submitted to multiple execution mechanisms without modification.
To run a Runnable on a new thread, you pass it to a Thread constructor and call start():
class FileScanner implements Runnable { public void run() { System.out.println("Scanning files on " + Thread.currentThread().getName()); } } Thread t = new Thread(new FileScanner(), "scanner-thread"); t.start();
With lambda expressions introduced in Java 8, implementing Runnable became even more concise because Runnable is a functional interface. You can write the same task inline:
Thread t = new Thread(() -> System.out.println("Scanning"), "scanner-thread"); t.start();
The real power of Runnable comes when you pair it with ExecutorService. Instead of managing thread creation manually, you submit Runnable tasks to a thread pool, which reuses threads efficiently. This avoids the overhead of creating a new OS thread for each unit of work and gives you better control over resource usage.
ExecutorService pool = Executors.newFixedThreadPool(4); pool.submit(() -> System.out.println("Task running")); pool.shutdown();
Runnable has one limitation: its run() method has no return type and cannot throw checked exceptions. If your task needs to return a result or propagate a checked exception, you should use the Callable interface instead, which returns a value through a Future object.
Interview tip: When asked to compare Runnable and Callable, note that Callable's call() method returns a generic type V and throws Exception, making it suitable for tasks that compute values or might fail, while Runnable is best for fire-and-forget background work.
Runnable vs Callable
Java provides two functional interfaces for defining concurrent tasks: Runnable and Callable. Choosing the right one depends on whether your task produces a result and whether it might throw a checked exception during execution.
Runnable is the older of the two, present since Java 1.0. Its run() method returns void and cannot throw checked exceptions. This makes it appropriate for side-effect-only tasks like logging, sending notifications, or updating a cache in the background. Any exception that occurs inside run() must be caught and handled internally, since it cannot be propagated to the calling thread.
Callable was introduced in Java 5 as part of the java.util.concurrent package. Its call() method returns a value of a generic type and declares throws Exception. When you submit a Callable to an ExecutorService, you receive a Future object that holds the eventual result. Calling future.get() blocks until the result is available and re-throws any exception the call() method raised, wrapped in an ExecutionException.
import java.util.concurrent.*; Callable<Integer> task = () -> 42; ExecutorService pool = Executors.newSingleThreadExecutor(); Future<Integer> future = pool.submit(task); System.out.println(future.get()); // prints 42 pool.shutdown();
Both interfaces can be used with anonymous classes, lambda expressions, or method references, since both are functional interfaces. In modern Java code, lambdas are the standard form.
You can also convert a Runnable to a Callable using Executors.callable(runnable, result), which returns a Callable that runs the Runnable and then returns the specified default result. This is useful when you need to unify different task types in a single pipeline.
Interview tip: Be prepared to explain what happens when future.get() is called and the underlying task threw an exception. The answer is that ExecutionException is thrown, and you must call getCause() on it to retrieve the original exception from the task.
Using Runnable with Thread Pools
Passing Runnable tasks to a thread pool is the standard approach for concurrent programming in production Java applications. Creating a raw Thread for every small unit of work is expensive because each Thread corresponds to an OS-level thread, and thread creation involves system calls and memory allocation for the thread stack. Thread pools solve this by maintaining a collection of reusable worker threads.
The Executors factory class provides several ready-made pool types. newFixedThreadPool(n) creates a pool with exactly n threads that persist until the pool is shut down. newCachedThreadPool() creates threads on demand and reuses idle ones, making it good for short-lived tasks with unpredictable arrival rates. newSingleThreadExecutor() runs all tasks sequentially on a single background thread, preserving submission order.
Here is a practical example of using a fixed thread pool:
ExecutorService pool = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { int taskId = i; pool.submit(() -> System.out.println("Task " + taskId + " on " + Thread.currentThread().getName())); } pool.shutdown(); pool.awaitTermination(10, TimeUnit.SECONDS);
Calling shutdown() tells the pool to stop accepting new tasks and to finish all pending ones. awaitTermination() blocks until all tasks complete or the timeout expires. For an immediate stop, shutdownNow() attempts to cancel running tasks by interrupting them, though completion is not guaranteed.
When a Runnable task throws an unchecked exception, the worker thread catches it and the exception is typically swallowed unless you set an UncaughtExceptionHandler on the thread factory. Always attach an exception handler in production code to avoid silent failures.
You can provide a custom ThreadFactory to the pool constructor to control thread naming, daemon status, and exception handling. This is important for observability in large systems where you need to quickly identify which pool a thread belongs to during debugging.
Interview tip: Describe the difference between shutdown() and shutdownNow(). Emphasize that shutdownNow() does not guarantee that running tasks are terminated; it only requests interruption, and tasks must check the interrupted flag to respond cooperatively.