Scenario where extending thread is preferred than implement Runnable? [duplicate] - java

This question already has answers here:
"implements Runnable" vs "extends Thread" in Java
(42 answers)
Closed 8 years ago.
As a beginner, I was reading about 2 ways of implementing Multithreading in Java.
I read this thread on SO and on many other threads.
It is stated that
"prefer runnable" , extends thread only when you are specialising Thread's behaviour.
Can someone explain me what is meant by specializing Thread behaviour by providing me a small piece of snippet which help me understand this line.

You should extend a Thread as much as you extend other library classes.
Take a List for example, more specifically ArrayList, you could add extra behaviour on it, like rejecting a value when adding if a certain predicate fails.
Then you can call that an PredicatedArrayList.
It is still a debate whether you want to extend ArrayList here or not, but that debate is not up for this question.
So an example of extending a thread would be a thread that kills itself after a specific amount of time. Then you would have SuicidingThread extends Thread, which could have a constructor taking the time.
This even fortifies the argument that you should put your actual tasks in a Runnable.
Like Runnable somethingRunnable = new SomeClass();, where SomeClass implements Runnable.
Now you can do either:
Thread someThread = new Thread(somethingRunnable);
Thread someThread = new SuicidingThread(somethingRunnable, 5, TimeUnit.DAYS);
So this would be an usecase for extending thread.

Specializing means, extend the functionality of existing Thread class. It could be anything depending on the application requirement. The one I've mentioned below may not be true logically.
public class MyThread extends Thread{
#Override
public void interrupt() {
if(thread has started some operation on database){
//roll back transaction
}
super.interrupt();
}
}
Here before interrupting the thread, we can check if any database operation is running currently and roll back it. Though it can be done from the interrupted catch block, handling it from extended class reduce the number of lines if you create lots of instances of this thread at different places in the application. It's just an example, nobody will use it this way. :)

Because java does not support for multi-inheritance.
If you have a class named Person.
class Person{
String name;
int age;
}
Then you want to create a class Man which extends Person
class Man extends Person{
}
Now you have used the extends keyword to declare that Man is a Person. Then if you want a Man to be performed like a thread,you can not extend Thread again because Java do not support for multi-inheritance.So just use Runnable interface which can be implements together with other interfaces.
class Man extends Person implements Runnable{
public void run()[
}
}
EDIT:
"extends thread only when you are specialising Thread's behaviour" means that your class is only a Thread which does not have other features,because when your class contains other features,you need to extends other super classed rather then the Thread class.As I have mentioned before,java does not support for multi-inheritance,so just extends thread only when you are specialising Thread's behaviour.

Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java so this class is specialized for Thread only.
By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.
Extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread then use Runnable interface instead.
Thread class has some behavior decided by JDK developers when you want to make some modification to it then you can extend your class with Thread class and modify it.

There are several reasons for preferring Runnable implementation over Thread extension:
Always prefer composition over inheritance and you will end up with less coupled code.
One way to decide how your class is related to Thread is to check the "is a" relation vs a "has a".
In practice extending Thread will force you to create new instances instances of your class for each thread, instead of sharing the same instance in the case of Runnable. See this.
Java supports only single inheritance
One example of legit use cases for extending Thread is when you need to design a Thread class with custom properties (ex: caching resources) that is being part of a CachedThreadPool

Related

When using a non thread safe class is a viable design to create multiple objects and pass it into each thread?

Say I have class A which is not thread safe, and I want to launch a bunch of threads with class B, is passing a new instance of class A to each thread of class B a good design choice, since if I passed one instance of class A to all of them there would be concurrency issues?
#NotThreadSafe
class A {
...
}
class B extends Thread {
private A a;
B(A a) {
this.a = a;
}
}
class C {
public static void main(String [] args) {
for(int i = 0; i < 10; i++) {
A a = new A();
B b = new B(a);
b.start();
}
}
}
It pretty much depends on the characteristics of class A.
In general, passing creating an instance of A per thread will solve (not solve, but rather eliminate) concurrency issues.
Assuming class A has some internal state (otherwise class A itself is supposed to be thread safe), each thread B will read/update different fields in memory that belong to its "own" object of class A, so no concurrency issue here, unless...
A is very "heavy" object and creating it will have a big performance / memory impact.
Using design of object per thread won't meet the functional requirements of the product. For example, you have to share something between threads (somthing = some common state) because if one thread B, say, has done some work and has updated that internal state, another thread B should be able to benefit from (be able to read) that state otherwise it will do that work again or do it in a wrong.
Let's assume that you have overridden run in the B class. Your example doesn't make sense otherwise. (The start() call would invoke Thread::run which returns immediately. Ooops!)
Some terminology first.
A thread confined object is an object is an object whose state is accessible to one and only one thread.
If an object is thread confined, then it doesn't matter if the class is thread-safe or not.
(Depending on how broadly you define "state" of course. Lets assume that the object's state is the closure of the object that the object's methods may access. Or something like that.)
So what we have in your example is a non-thread-safe object a that is created in main and then used solely in a single child thread.
Prior to the start() call, each a is thread confined to the main thread. For this part of the program, thread-safety (of A) doesn't matter.
Once control reaches the child thread's run() method, each a is thread confined to the child thread. From then on, thread safety doesn't matter.
Now what about the start() call itself?
The Java Memory Model (JLS 17.4) specifies that there is a happens-before relationship between the call to start() in the main thread, and the call to run() in the child thread. This happens-before ensures that writes to the A or B instances or anything else made by the main thread prior to the start() call are guaranteed to be visible to the child thread on / after entering the run method body. This is a strong guarantee. Any compliant Java 5.0 or later implementation will behave this way, on any platform.
However, changes made to the A, etc in the main thread after the start() call are not guaranteed to be visible to the child. They may or may not be. If that happens, your code is likely to be broken. But the example code doesn't show it happening.
In summary, this approach is thread-safe. Whether it is "viable" depends on whether your design meets the requirements. For example, the B threads need to share state, this approach doesn't address that.
Finally, extending Thread is generally thought to be a bad idea. A better idea would be to instantiate plain Thread instances, passing them a Runnable as a constructor parameter. Alternatively, use an ExecutorService and let that take care of thread management.
There is a big difference between using a single instance and a new instance each time. (Eg if the class represents a Person then, it's the difference between the same person or a different one every time. This makes the program outcome different between circumstances and this question therefore doesn't make sense.)
If we assume the class holds no data and therefore the program outcome will not change whether or not a single instance or multiple are used, then
a good design choice, since if I passed one instance of class A to all
of them there would be concurrency issues
it would be a terrible design choice and not solve any concurrency issues, as the external data each class instance works on will still be the same and the threads will fight over the data.
To fix concurrency issues you must use synchronization.

What is the function of this class? [duplicate]

This question already has answers here:
What is an interface in Java?
(13 answers)
Closed 3 years ago.
What does "implements Runnable" mean?
I am sending data from arduino to this java file
public static class SerialReader implements Runnable {
InputStream in;
public SerialReader( InputStream in ) {
this.in = in;
}
implements is a keyword in java for implementing an interface.
Acording to Oracle:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. The class must
define a method of no arguments called run.
This interface is designed to provide a common protocol for objects
that wish to execute code while they are active. For example, Runnable
is implemented by class Thread. Being active simply means that a
thread has been started and has not yet been stopped.
In addition, Runnable provides the means for a class to be active
while not subclassing Thread. A class that implements Runnable can run
without subclassing Thread by instantiating a Thread instance and
passing itself in as the target. In most cases, the Runnable interface
should be used if you are only planning to override the run() method
and no other Thread methods. This is important because classes should
not be subclassed unless the programmer intends on modifying or
enhancing the fundamental behavior of the class.
Source
implements is for implementing an interface.
and
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Why does Thread Class implements Runnable Interface [duplicate]

This question already has answers here:
Why does Thread implement Runnable?
(2 answers)
Closed 5 years ago.
First of all i have gone through similar question but couldn't get my answer, like -
Why does Thread implement Runnable?
So my question is that Runnable contains only run method which is there is Thread class itself then why does Thread Class implements Runnable Interface and what functionalities does implementing Runnable provides to Thread class, what will happen if Thread class does not implements Runnable.
"The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. [...]
This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread."
oracle doc
But I think what your exactly looking for is here. The answer given was "backward compability".
Sometimes Java needs to make choices, and they always chose solutions dealing with backward compability.
If Thread class doesn't implement Runnable then Thread class will not have run method. Then jvm will not treat it as a thread at all.

how just by implementing an interface subclass acquires the behaviour

I always wonder how just by implementing an interface , sub class acquires the behavior. For example if I implement Runnable interface my subclass start behaving as thread, but what if I implement all the methods defined in interface Runnable but not write "implementing Runnable", subclass doesn't behave as Thread. Same with EventListeners . Please help me understanding this behavior.
By implementing an interface I, you're declaring that the Object "is a" I and that it'll contain all the methods defined by this interface. If you just implement the methods of the interface I, but don't declare it by an implement statement, compiler won't be able to determine that your class "is a" I and you won't be able to use it as a I-type.
No, Runnable has nothing to do with behaving like a thread. It just contains a plain, simple, void nullary method called "run".
Not specifying implements Runnable will just make your object not an instance of the Runnable type, which means you won't be able to pass it to a method requiring a Runnable. This is just an issue of type safety. The method you call could also accept an Object and invoke run using reflection, with the exact same behavior.
When you are implementing Runnable your class does not become thread and does not start behavior as thread. However if your class implements Runnable you can run it in context of thread:
class MyClass1 implements Runnable {
public void run() {
// this stuff will run in thread when thread's start() method is called
}
}
new Thread(new MyClass1()).start();
But java is strongly typed language. You can just create class like this:
class MyClass2 {
public void run() {
// this stuff will run in thread when thread's start() method is called
}
}
But it will not be Runnable. Therefore you cannot just send it to thread:
new Thread(new MyClass2()).start();
In this case you will get compilation error. Compiler cannot know that your class indeed implements method that looks like one that is declared in Runnable. You must declare this (as in first case).
A Runnable only allows your class to be run in a Thread. You still need e.g. a java.util.concurrent.Executor to actually run it in an actual Thread.
However, you can extend Thread which would allow you to call Thread.start().
To actually get out behavior from just implementing an interface, you would need a second object inspecting the classpath for classes implementing your interface using reflection, and then do something with that class.
Your question has two aspect:
Interface as a contract: Interfaces imposes a behavioral contract on a class implementing it. For example, If Car is an interface with some methods abstractly defining a car, any class implementing Car interface will have to define the methods of the car. You are free to actually implement the behavior.
Analogy of Runnable acting as thread is incorrect. What makes Runnable class act as thread is the the Thread class. Runnable just specifies the contract for a class to act as thread. Check this post.
This is not a subclassing behavior. In order to use subclass behavior you need to extend the class.
W.r.t interfaces these are just templates/contracts that are implemented by class. In order for runnable to work calling program need to instantiate a thread and when thread will start it will call run method implemented by your class.
I always wonder how just by implementing an interface , sub class acquires the behavior.
It doesn't 'acquire' any 'behaviour'. The subclass provides the behaviour. What implementing the interface does is provide the compile-time type signatures such that you can use the subclass where the interface is specified.

Use of creating a Thread by extending a Thread class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
Java provides two options to create a Thread class i.e either by implementing Runnable or by extending Thread class.
I know there can be many reasons to implement a Runnable but not sure where the scenario would be to extend a Thread class to create own Thread class?
Could you please provide me scenarios where extending Thread seems to be feasible or better option or advantageous...
There was a
Question on the threads but that did'nt answer my question
There is almost no reason to extend Thread, basically the only reason you would want to extend thread is if you were going to override things other than run() which is generally a bad idea. The reason it is less common to extend Thread is because then the class can't extend anything else, and if you're only overriding the run() method, then it would be kinda pointless to extend Thread and not implement Runnable.
Runnable is an interface with just one method run() that needs to be implemented by the class implementing the interface.
e.g.
public class MyRunnable implements Runnable {
#Override
public void run() {
//...
}
}
MyRunnable is not a Thread nor can you create a new thread just by using that class. So, it doesn't quite make sense to say -
Java provides two options to create a Thread class i.e either by implementing Runnable ...
You can extend the Thread class but just like #John said there isn't any point in doing so.
But if you want to execute some code in a new thread then the following is the best way -
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
t.start() method starts a new thread and invokes run() method on r (which is an instance of MyRunnable.

Categories