Why does java.util.concurrent.RunnableFuture have a run() method? - java

As I was going through JDK 7, I found that java.util.concurrent.RunnableFuture<V> has a run method. I wonder what the significance of duplicating the same run method signature in the interface is when it already extends Runnable.
package java.util.concurrent;
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}

It's defined in the interface so that they can attach RunnableFuture-specific JavaDoc to it. There's no technical significance.

There are no docs that provide such explanation. So I am going to provide my opinion.
I dont think it has any major significance. Imagine how the interface world look
public interface RunnableFuture<V> extends Runnable, Future<V> {
}
Though it is perfectly valid it does not clearly indicate its purpose. So in my opinion it is just been provided for easy understanding for run() method specific to RunnableFuture interface. So that you know to put your runnable logic by overriding run() method.
Another point that I can think of is Runnable is one of the early interfaces and if you see the run() method it is
public abstract void run();
and public and abstract keywords are redundant as methods in an interface are by default public and abstract. To improvise this might be one of the reasons.

Related

Quick Java Anonymous function/class question

I know how anonymous functions work in JS and all but a bit confused on parts of it in Java.
So below I have an anonymous class (I'm just using the Thread class as an example to what I've seen), where I override the run() function and then call .start() on that class.
new Thread() {
#Override
public void run() {
System.out.println("Hello from the anonymous class thread");
}
}.start();
So this works, but IntelliJ wants to me re-write it as this:
new Thread(() -> System.out.println("Hello from the anonymous class thread")).start();
I get most of this syntax, but just a bit confused as to how the run() function is being overridden. From my understanding, there is no parameter being passed into the Thread class (so nothing being passed into the constructor I'm assuming). Now where I'm confused is here. It doesn't state anywhere that it is overriding the run() function. Is this a special case for the Thread class or is there something I am missing?
Hope that I explained this clearly and thanks in advance!
The syntax that IntelliJ proposes to you is not more of an "oblique" translation of your original code, and does not actually override Thread.run like your original code does.
Your original code creates an anonymous subclass of Thread with run overridden, whereas the proposed syntax by IntelliJ calls this constructor of Thread that accepts a Runnable. The lambda expression represents the Runnable. If we "expand" the lambda expression into an anonymous class, we will be actually doing this:
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Hello from the anonymous class thread");
}
}).start();
So we are creating an anonymous implementation of Runnable, and implementing Runnable.run instead.
It doesn't state anywhere that it is overriding the run() function.
True, but run is the only abstract method in the Runnable interface, so Java is able to figure out that you are overriding that method.
The run() function is being overridden implicitly because it's the only method of the Runnable interface, which makes it a functional interface. A functional interface has exactly one abstract method. This special property of an interface allows you to implement it implicitly using a lambda expression. The compiler knows you're providing an implementation of the Runnable.run() method, because it's the only method inside the interface.
If you take a look at the Runnable interface, you'll see that it is decorated with the #FunctionalInterface annotation. This annotation ensures that the decorated interface can never have more than one abstract method (or else the compiler will fail). Note that this annotation is not required in order for the implicit lambda feature to work.

Why is Thread not an abstract class and start() not final?

Why was the Thread class implemented as a regular class and not an abstract class with run() method being abstract.
Will it possibly introduce any problems? Or does it have any use in being this way?
Also, the Thread.start() method is supposed to be a very specific method whose functionality cannot be implemented by any other class (If I am not wrong). And hence I guess the final keyword would be apt for this more than any other method.
But I am able to override this method and use it as I like,
public class Test extends Thread {
public static void main (String... args) {
Thread test = new Test();
test.start();
}
#Override
public void run() {
System.out.println("New thread started...");
}
#Override
public void start() {
System.out.println("Did anyone tell you I will spawn a new thread??");
}
}
It obviously only printed,
Did anyone tell you I will spawn a new thread??
Is there any use in overriding other than confusing the engineer replacing you?
If not, why was the method not declared final in Thread class?
You can of course choose to shoot yourself in the foot, but that doesn't mean you must.
Why was the Thread class implemented as a regular class and not an abstract class with run() method being abstract.
Because the recommended way to create a start a thread is not to subclass Thread. The recommended way is to define a Runnable, and pass it as argument to the Thread constructor:
Runnable r = new Runnable() {
#Override
public void run() {
...
}
};
Thread t = new Thread(r);
t.start();
And hence I guess the final keyword would be apt for this more than any other method.
Yes and no. You can't replace the implementation of start() by your own implementation, but you can do additional things in start() if you want:
#Override
public void start() {
System.out.println("Did anyone tell you I will spawn a new thread??");
super.start();
}
That said, if Java was redesigned from scratch today, there is a good chance the design would be different. Remember that this class dates from Java 1.0, and is still backward-compatible.
Why was the Thread class implemented as a regular class and not an
abstract class with run() method being abstract.
This question actually boils down to the fact that you should always prefer composition over inheritance.
If the Thread class was declared as abstract, the language would have to provide another class that extended from it which programmers could use to create a Thread. Your question would then be about why this class that extends from Thread is not abstract. If the language did not provide another class that extends from Thread, programmers would have to create their own class that extends from Thread and override the run() method.
If not, why was the method not declared final in Thread class??
The only possible explanation I can give is that the developers of the language saw some use-cases for overriding start when the class was introduced to the JDK. The first version of Java that I used was 1.5 and I personally have not come across a use-case where I found the need to override start. As JB Nizet stated in his answer
if Java was redesigned from scratch today, there is a good chance the design would be different
Why is Thread.start() not final?
Are you sure you would never want to override it?
Class MyThreadFactory implements ThreadFactory {
#Override
public Thread newThread(Runnable r) {
return new Thread(r) {
#Override
public void start() {
LOGGER.info("Starting thread " + this);
super.start();
}
};
}
}
I feel a few calirifcations should be posted for the answers :
"Are you sure you would never want to override it?"
No ! I would not. Thats like saying, "Are you sure , you want to declare this variable private?" Because if I could declare any variable I use as public without fearing that other developers may mess my design logic, coding would be a breeze. One of the most important purpose of OOPS concepts of Scope, abstraction, polymorphism, Error handling etc is to communicate to other developers the design and intentions behind your code.As pointed out in the question, when you override start method, nobody is forcing you to use super.start(). #Codebender wrote a start method for a thread without using super.start() and compiler never complained. So he is free to break the whole mechanism of Threading and compiler is suppose to just let it pass? Thread's start method ensures that run method is called and execute at the right time ! It is critical to the very concept of Threading. I would be more than happy to be corrected, if I missed something here.
2.
Because the recommended way to create a start a thread is not to
subclass Thread.
OK, if codebender is allowed by design, to sublass Thread and mess up the start method, By that logic, it is the design shooting itself in the foot.
By another statement made,(which I agree with completely) , Runnable is the recommended way. Then why do we allow Thread class at all to instantiate the thread at all with no restrictions? This is followed by :
You can't replace the implementation of start() by your own
implementation,
That actually supports codebender's claim that start method should be final when you say that.. ^
The one point, that's valid, is mentioned already as a side note, but is the actual answer to this question
"Backward compatibility".
In fact, improvements were even going on as late as JDK 5.0 , when they incorporated many major additions and clarifications to the Java concurrency model. We want backward compatibility to be supported all the way and thats why Thread class is still exactly as it was before, even though Runnable interface is the recommended way nowadays.
Again, I would be more than happy to be corrected, if I missed something.

Lack of optional methods/operations of an implemented interface causing errors

** not sure if its obvious, but I am writing java
I have been trying to complete an assignment for a class of mine which requires me to implement the ListIterator<String> interface for a class. I do not wish to implement remove(), add(), or set(), which are the optional methods for the interface. But now that it is implemented, Eclipse is giving me errors saying I need to implement those methods. Does anyone know why that is or how I can solve that? Thank you in advance for your help.
They're not really optional.
You have to provide some sort of implementation, but it's common to provide an implementation that just throws an exception:
public void remove() {
throw new UnsupportedOperationException();
}
In some situations it might also be reasonable to provide a "do-nothing" implementation:
public void remove() {
// Can't remove...
}
If you do either of these, it's a good idea to document that you've done it.
If you make this an abstract class, then you don't have to implement the methods in this specific class. But at some point down the class hierarchy, you have to implement a concrete class with all the methods. Nothing actually happens until you instantiate your class in an instance, and you can't do that with an abstract class.
Interface methods are not optional, but rather insure that the class implementing the given interface implements all its methods unless it is an abstract class. When a class implements a certain interface it can be referred to as the type of the interface according to the concept of polymorphism in Java.
Example below:
public interface Herbiverous {
void eatsPlants();
}
public class Human implements Herbiverous{
public void eatsPlants() {
System.out.println("I eat plants");
}
public static void main(String[]args) {
Herbiverous h = new Human();
//in which case you can only apply the methods of the interface
h.eatsPlants();
}
}
Hope this was insightful.

questions on implementing Runnable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
I have two questions about multithreaded programming. I read a few answers on the internet, but still I can't find a satisfying answer.
Implementing the Runnable is preferred over extending the thread class. Why?
How is it that we are able to get away with overriding just the run() method?
According to 'The Complete Reference to Java' by Herbert Schildt, If we are not overriding any methods of Thread class other than run(), it's better we implement Runnable.
My 2nd question might sound a bit silly, but I seem to be missing something and I'm not sure about how the whole thing works.
1: Implementing the Runnable is preferred over extending the thread class. why?
Because it allows your class to extend another class if it wants to instead of being forced to extend Thread.
2: How is it that we are able to get away with over-ridding just the run() method?
You can certainly override other methods but the Thread object will call the run() method when the thread is started. That's how it works. The default Thread.run() method is:
public void run() {
if (target != null) {
target.run();
}
}
If you call the Thread constructor with a Runnable then that is what the target is set to. If you instead extend Thread and #Override the run() method then that is the method that will be called when the thread object is started.
That's how the Thread class works.
2: How is it that we are able to get away with over-ridding just the run() method?
You may have misspoke here and were instead asking why we only need to implement the run() method in Runnable().
Runnable is an interface with a single run() method that you must implement.
Thread is a concrete class that you are extending. You can override any methods in a concrete class unless the class is final or the method is final.
Make sure you use proper Java terminology and don't mixup implement and override.
Three fundamentals before you delve deeper.
A class can only extend one class.
A class can implement any number of interfaces.
An interface can extend any number of interfaces.
Additionally, an abstract class is a class. So it behaves like a class and you can't implement it. You only extend it.
There are a number of traps which can occur if you extend Thread which you don't get with implementing Runnable.
public static String getName() {
return "My Test Application";
}
public static void stop() {
System.out.println("Shutting down");
}
public static void main(String... args) {
new Thread() {
#Override
public void run() {
System.out.println(getName());
stop();
}
}.run();
System.out.println("Bye now.");
}
prints
Thread-0
Bye now.
See how many bugs you can spot.
Unnecessary inheritance is generally a bad idea. You might hear "prefer composition over inheritance" often enough. I'm sure google can pull up enough links for you. The general issue is that inheritance bring tight, unnecessary coupling between classes.
Same goes for GUI components, btw.

extend/inherit from 2 classes in Java

I've read up on this topic and it seems my best option is to make one of the classes that I want to extend into an interface..
The thing is that ParentA is a class from the Android API, so I can't actually modify it (I only have the build), and ParentB was made by a friend, ParentB already implements Runnable (and AFAIK you can't have an interface that implements another interface.. I get errors anyway).
You can't have an interface that implements another interface, since interfaces have nothing to do with implementation. You can, however, have an interface that extends another interface. You can also have a class that implements two different interfaces.
When you have two potential parents for your subclass and they don't subclass each other, the thing you need to ask yourself is whether your class isa ParentA or isa ParentB. Which one fits better? Once you decide that, you turn the other one into a hasa.
So let's say that you decide your class isa ParentA. Your code could look something like:
public class MyClass extends ParentA {
private final ParentB runnable;
private final Thread runningThread;
public MyClass(ParentB runnable) {
this.runnable = runnable;
this.runningThread = new Thread(this.runnable);
}
public void start() {
this.runningThread.start();
}
public void interrupt() {
this.runningThread.interrupt();
}
public boolean isAlive() {
return this.runningThread.isAlive();
}
}
Here I am delegating thread methods rather than ParentB methods, since that is what you will most likely want to control on a Runnable. If ParentB has its own behaviour that you want to expose, then you will need delegation methods for those as well.
In Java you can extend interfaces.
But for your case I would suggest using a aggregation pattern or a delegation pattern.
Take a look at the Java Design patterns: http://en.wikipedia.org/wiki/Delegation_(programming)

Categories