JAVA

Java Runnable vs Callable – What's the Difference?

neal89 2025. 3. 25. 13:04

 

When working with Java’s concurrency API, you’ll often encounter two key interfaces: Runnable and Callable.

At a glance, they may seem similar — both are used to represent tasks that can be run by a thread.
But they have a few important differences.


✅ Key Differences

Feature Runnable Callable

Return value ❌ No return ✅ Returns a result (V)
Checked exceptions ❌ Cannot throw ✅ Can throw checked exceptions
Introduced in Java 1.0 Java 5 (with java.util.concurrent)
Common use with Thread, Executor ExecutorService.submit()
Supports Future result ❌ No ✅ Yes

🔍 When to Use Which?

  • Use Runnable when you just want to run some background code, and you don’t care about the result.
  • Use Callable when you need a result from the task, or want to handle exceptions properly.

💡 Example: Runnable vs Callable

import java.util.concurrent.*;

public class RunnableVsCallableExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // Runnable: no return value
        Runnable runnableTask = () -> {
            System.out.println("Runnable task is running");
        };
        executor.execute(runnableTask); // No result returned

        // Callable: returns a result
        Callable<String> callableTask = () -> {
            Thread.sleep(1000); // Simulate work
            return "Callable task completed";
        };
        Future<String> future = executor.submit(callableTask);

        // Get the result from the callable
        String result = future.get(); // Blocks until result is ready
        System.out.println("Callable result: " + result);

        executor.shutdown();
    }
}

🧠 Summary

  • If your task does not return anything, go with Runnable.
  • If your task needs to return a value or throws checked exceptions, use Callable.
  • When working with thread pools (ExecutorService), Callable + Future is extremely useful.

'JAVA' 카테고리의 다른 글

Java ExecutorService – invokeAll() vs invokeAny()  (0) 2025.03.25
Java Future  (0) 2025.03.25
intro Executor  (0) 2025.03.25
Java Concurrent Collections (Synchronized Collections vs. Concurrent Collections)  (0) 2025.03.18
Atomic operations and cas  (0) 2025.03.18