Prefer Implementing Runnable Over Extending Thread

ID

java.prefer_runnable_over_thread

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

best-practice, concurrency

Description

Reports classes that extend Thread directly instead of implementing Runnable.

Rationale

Extending Thread couples the task logic with the threading mechanism. Since Java only supports single inheritance, extending Thread also prevents the class from extending any other class. Implementing Runnable (or Callable) instead allows the task to be decoupled from the execution mechanism and submitted to an ExecutorService or thread pool.

// Bad -- extends Thread
class Worker extends Thread {
    public void run() {
        doWork();
    }
}

Remediation

Implement Runnable and pass it to a Thread or ExecutorService:

// Good -- implements Runnable
class Worker implements Runnable {
    public void run() {
        doWork();
    }
}

// Usage with ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(new Worker());