Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why isn't Thread class final? Why would you extend a Thread ever?

I got this as an interview question.

why isn't Thread class final? Why would you extend a Thread ever?

I could not come up with real world use cases.

like image 413
user2434 Avatar asked May 02 '12 14:05

user2434


2 Answers

From Oracle's documentation:

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. The other way to create a thread is to declare a class that implements the Runnable interface.

So the answer is "you may want to subclass Thread to override its run() method."

The quoted paragraphs have been in the Java documentation going back as far as JDK 1.1. Java has added other convenient classes for managing concurrency, most notably, the executors mentioned in the comments, possibly diminishing or eliminating the need to extend Thread. They cannot make it final, however, because that would break backward compatibility.

As far as practical reasons go, I think the only reason you may want to extend Thread rather than implement Runnable today would be to override its methods other than run(). For example, you may want to add logging or additional clean-up.

like image 174
Sergey Kalinichenko Avatar answered Oct 12 '22 10:10

Sergey Kalinichenko


This is pretty much just taken from John Vint's comment, but I think it's the best answer.

The only time I can think of where I might extend Thread rather than implementing Runnable -- or, even better, just using an ExecutorService with a Future -- is when I needed to override Thread.interrupt() to do some cleanup. Otherwise, I can't see any practical reason to actually extend Thread.

like image 36
Tim Pote Avatar answered Oct 12 '22 09:10

Tim Pote