Easy java java-21

What is the difference between Thread, Runnable and Callable?

The 30 second answer

Thread is the worker: a class that implements Runnable and represents a thread of execution. Runnable is the work, a run method with no result. I prefer submitting a Runnable to an executor rather than subclassing Thread. Callable is similar, but call returns a value and can throw a checked exception. I submit a Callable to an ExecutorService, get a Future back, and call get when I need the result or to see a failure.

Could you say this in an interview?

Thread is "a thread of execution in a program," and the class implements Runnable. Starting a thread schedules its run method. You can subclass Thread and override run, or pass a Runnable into a Thread constructor. The Thread Javadoc says most applications should have little need to extend Thread. In production I submit work to an ExecutorService instead of calling new Thread(...).start() myself, so the pool, naming, and shutdown are explicit.

Runnable is the work with no result: a functional interface whose method is void run().

Callable is, in its Javadoc's words, "similar to Runnable," but call() returns a value and may throw a checked exception. Runnable does neither.

ExecutorService pool = Executors.newFixedThreadPool(4);

pool.execute(() -> persist(event));                 // Runnable, no Future
Future<?> fired = pool.submit(() -> persist(event)); // Runnable, Future for completion
Future<Integer> count = pool.submit(() -> dao.count()); // Callable

int n = count.get();   // waits; wraps a task exception in ExecutionException

Executor.execute accepts only a Runnable and does not return a Future. ExecutorService.submit accepts a Runnable or a Callable and returns a Future. The Javadoc for ExecutorService states that actions before submit happen-before the task, which in turn happen-before the result is retrieved with Future.get(). If I use submit, I must eventually call get (or join on a CompletableFuture); otherwise a failure stays inside the Future and can be missed. execute does not capture the exception that way; it goes to the thread's uncaught exception handler.

Sources (5)
  1. Thread Javadoc (Java 21)docs.oracle.com
  2. Runnable Javadoc (Java 21)docs.oracle.com
  3. Callable Javadoc (Java 21)docs.oracle.com
  4. ExecutorService Javadoc (Java 21)docs.oracle.com
  5. Future Javadoc (Java 21)docs.oracle.com