Lambda: Callable variable initiated with a Runnable instance - java

Just found a strange and interesting Lambda behavior.
Let's have the following class:
private class Task implements Runnable {
#Override
public void run() {
// something to process
}
}
The following statement is compiling and running:
Callable task = Task::new;
Could somebody explain why this is possible ?
EDIT:
Based on answers below, check the following statements:
1.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(Task::new);
2.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Task());
On the first glance, seems the same, but actually does a totally different thing.
What happens here is exactly the above situation.
The reason is that ExecutorService has two methods:
submit(Runnable);
submit(Callable);
So, using the code from 1. the executor will process the following on it's internal thread:
new Task()
The version from 2. will actually call the submit(Runnable) method and the code from Task.run will be executed.
Conclusion: just be careful with Lambdas :)

The Callable is not initialized with a Runnable instance, it is initialized with a method reference to the Task constructor that will produce a Runnable when executed.
In other words, if you execute that Callable, it will return a new Task object that has not yet been run. That Task implements Runnable is actually completely irrelevant here.
This would be clearer if you didn't use the raw type. Task::new can be assigned to Callable<Task> because it is something that takes no parameters and returns a Task.

To implement the Callable<V> interface one must implement a method with the signature V call().
Therefore, you can implement this interface with method references of any methods that take nothing and return some reference type, which includes constructor method references such as Task::new.
In fact, any class having a parameter-less constructor can be used this way:
Callable<SomeClass> callable = SomeClass::new;

Related

Will methods in lambda only be evaluated when the lambda is executed?

Can we be sure that methods being called in a java lambda are only being called when the lambda itself is executed, and never in advance?
If you take a look at my code:
StringBuilder myStringBuilder = new StringBuilder("my result");
Supplier<String> mySupplier = () -> "result: " + myStringBuilder.toString();
myStringBuilder.append(", after appending.");
System.out.println(mySupplied.get());
Can we be 100% certain that the result will always be:
result: my result, after appending
And never just
result: my result
Consider the following snappet:
Runnable runnable = () -> expensiveMethod(); // Runnable not called
firstMethodCall(); // Runnable not called
secondMethodCall(); // Runnable not called
runnable.run(); // HERE IT COMES, Runnable IS called
The lambda expression is nothing else than the implementation of an anonymous class with one method (this secures #FunctionalInterface annotation).
Runnable runnable = new Runnable() {
void run() {
expensiveMethod();
}
};
// runnable's method is not executed since the method run is not called
// the runnable.run() invokes the expensiveMethod()
The Java 8 specification 15.27. Lambda Expressions explains that the expression is called when the appropriate method of the functional interface is invoked:
Evaluation of a lambda expression produces an instance of a functional interface (§9.8). Lambda expression evaluation does not cause the execution of the expression's body; instead, this may occur at a later time when an appropriate method of the functional interface is invoked.
Yes. The lambda code only executes when called not when the containing line is executed.
As per the spec
Lambda expression evaluation does not cause the execution of the expression's body; instead, this may occur at a later time when an appropriate method of the functional interface is invoked.
Lambda is like implementation code of an interface and just like an interface implementation, it will only be executed when you call it.
Lamba is an implementation of a Functional Interface. Its content will be changed / computed at the time of its call.
So, yes, you can 100% be sure about your assumption :)

Are Constructors Synchronized Until Totally Complete?

I'm building a program that requires the construction of some objects that require such intense computation to create, my smartest course would be to have them built in their own dedicated threads, while the master thread keeps grinding away on other things until the objects are needed.
So I thought about creating a special class specifically designed to create custom objects in their own thread. Like so:
public abstract class DedicatedThreadBuilder<T> {
private T object;
public DedicatedThreadBuilder() {
DedicatedThread dt = new DedicatedThread(this);
dt.start();
}
private void setObject(T i) {
object = i;
}
protected abstract T constructObject();
public synchronized T getObject() {
return object;
}
private class DedicatedThread extends Thread {
private DedicatedThreadBuilder dtb;
public DedicatedThread(DedicatedThreadBuilder builder){
dtb = builder;
}
public void run() {
synchronized(dtb) {
dtb.setObject(dtb.constructObject());
}
}
}
}
My only concern is that this mechanism will only work properly if the master thread (i.e. the thread that constructs the DedicatedThreadBuilder) has a synchronized lock on the DedicatedThreadBuilder until it's construction is completed, and therefore blocks the DedicatedThread's attempt to build the product object until it has finished construction of the DedicatedThreadBuilder. Why? Because the subclasses of DedicatedThreadBuilder will no doubt need to be constructed with parameters the will need to be passed into their own private storage, so that they can be used in the constructObject() process.
e.g.
public class JellybeanStatisticBuilder extends DedicatedThreadBuilder<JellybeanStatistics> {
private int greens;
private int blacks;
private int yellows;
public JellybeanStatisticBuilder(int g, int b, int y) {
super();
greens = g;
blacks = b;
yellows = y;
}
protected JellybeanStatistics constructObject() {
return new JellybeanStatistics(greens, blacks, yellows);
}
}
This will only work properly if the object is blocked to other threads until after it is completely constructed. Otherwise, the DedicatedThread might try to build the object before the necessary variables have been assigned.
So is that how Java works?
I think what you want is to have some sort of synchronised factory class:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class SyncFactory<T> {
// alternatively, use newCachedThreadPool or newFixedThreadPool if you want to allow some degree of parallel construction
private ExecutorService executor = Executors.newSingleThreadExecutor();
public Future<T> create() {
return executor.submit(() -> {
return new T();
});
}
}
Now you'd replace usages of T that may need to happen before T is ready with Future<T>, and have a choice between calling its Future.get() method to block until it's ready, set a timeout, or to call Future.isDone() to check up on the construction without blocking. In addition, instead of polling the Future, you may want to have the factory call a callback or post an event to notify the main thread when it has completed construction.
If (big if) this is truly needed (think that one over first)...
The overall idea you are heading toward can work, but your code is confusing and, at first glance by me anyway, appears that it might not work. This type of complexity which can break things is a very good reason to double-think and even triple-think heading down this path.
The major problem I spotted right away is that you are only ever creating 1 instance of the object. If this is a factory which just creates things on another thread, then the DedicatedThread should be called upon in DedicatedThreadBuilder's constructObject, not in its constructor.
If, on the other hand, you actually intend for the DedicatedThreadBuilder to only create 1 instance of T, then this abstraction seems unnecessary... just move DedicatedThread's behavior out to DedicatedThreadBuilder, as DedicatedThreadBuilder doesn't really seem to be doing anything extra.
Second, a minor thing that isn't incorrect so much as it is just unnecessary: you have an inner class which you pass an instance of the outer class to its constructor (that is, DedicatedThread's constructor takes a reference to its parent DedicatedThreadBuilder). This is unnecessary, as non-static inner classes are already linked to their outer classes, so the inner class can reference the outer class without any extra reference to it.
Third, if you move the behavior out of the constructor and into a separate method, then you could synchronize that. Personally, I would have had the constructObject be the thing that kicked off the process, so that calling dtb.constructObject() started the object's creation, and constructObject itself set object = newlyCreatedThing when it was done. Then you could synchronize that method if you want, or do whatever, and not have to worry about the constructor possibly not behaving how you want - in my opinion you should not generally have to worry that a constructor might have some odd side effects.
Fourth, do you have any way to know when the object is ready and available for getting? You might want to add some mechanism for that, such as an observer or other callback.
The problem is that you are using the subclass before it is constructed. It doesn't really have anything to do with multithreading. If you were calling constructObject directly from the DedicatedThreadBuilder constructor, it would be just as bad.
The reasonable implementation that is closet to what you have is just to provide DedicatedThreadBuidler with a separate start() method that should be called after the object is constructed.
Or you could have it extend Thread and use the Thread methods.
Or you could have it implement Runnable so you could use it with a Thread or an Executor or whatever.

Execute runnables in a list

I have a list of runnables that I would like to call using lambda expressions:
Arrays.asList(runnable1, runnable2, runnable3, ...).forEach(r->r.run());
Is there a 'better' (more efficient) shortcut to call the Runnables run() method other than the following way?
Arrays.asList(runnable1, runnable2, runnable3, ...).forEach(Runnable::run);
I think this expression will be translated to a Runnable wrapping the runnable instance in the list.
EDIT:
My assumption/concern (maybe wrong) is that the compiler will translate the expression list.forEach(Runnable::run) to something like this, and thus not 'efficient':
list.forEach(r -> new Runnable() {
#Override
public void run() {
r.run();
}
});
Whether you write
Arrays.asList(runnable1, runnable2, runnable3, ...).forEach(r->r.run());
or
Arrays.asList(runnable1, runnable2, runnable3, ...).forEach(Runnable::run);
in either case, there will be an instance of Consumer generated, as that’s what Iterable.forEach expects.
The consumer will be equivalent to
Arrays.asList(runnable1, runnable2, runnable3, ...).forEach(new Consumer<Runnable>() {
public void accept(Runnable r) {
r.run();
}
});
but that’s not a wrapper around a runnable, as it encapsulates an action applied to arbitrary Runnable instances passed in as parameter. Hence, there is at most one Consumer instance created for the entire forEach operation.
As explained in this answer, the JVM will be responsible for the creation of the Consumer instance and has the freedom to reuse existing instances, which happens in practice with the current implementation and non-capturing instances of functional interfaces, which applies to both variants, using a lambda expression or a method reference, so there will be only one Consumer instance, reused even on subsequent evaluations of the statement.
The only difference with current compilers is that the lambda expression r->r.run() will generate a method within your class calling the run() method whereas for the method reference, the runtime generated Consumer implementation class will call it directly, which makes the method reference more efficient on the hard-to-ever-measure scale.

What's the difference between different ways to start a thread?

I have a class named MyThread which extends the Thread class and implement the run() function.When I want to run it , I got two ways:
new a instance and call the function,like: new MyThread().start()
new a instance and transmit the instance to the construction function of Thread as a parameter and then call the start function of Thread. Like this: (new Thread(new MyThread)).start();
Anybody can just tell the difference?
Because you've said your class extends Thread, the second one is a bit redundant. In your second example, you're not using your class as a Thread, you're just using it as a Runnable.
Normally, you'd either extend Thread and then call its own start (your #1), or you'd implement Runnable and then use a Thread to run it (your #2). But you wouldn't extend Thread and then use another Thread to run it.
In terms of what's different, if you need to do anything to control or interrogate the thread, in your first case you'd use the Thread methods on the instance of your class; in the second case, you'd use them on the instance you create with new Thread. If you extend Thread but run it via #2, the Thread methods on your instance are irrelevant and could be confusing.
That last bit is probably clearer with examples:
Example of extending Thread:
class Foo extends Thread {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Start it
foo.start();
// Wait for it to finish (for example)
foo.join();
Note we started and joined the thread via the foo reference.
Example of implementing Runnable:
class Foo implements Runnable {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Create a Thread to run it
Thread thread = new Thread(foo);
// Start it
thread.start();
// Wait for it to finish (for example)
thread.join();
Note we started and joined the thread via the thread reference.
Don't do this:
class Foo extends Thread {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Create a Thread to run it -- DON'T do this
Thread thread = new Thread(foo);
// Start it
thread.start();
...because now you have Thread#join available on both foo and thread; which is the right one to use? (The answer is: The one on thread, but it's confusing, so it's best not to do that.)
Well, you have two method to implement a multi-thread.
extend Thread and use new MyThreand().start() to start your thread.
implement Runnable interface. In this condition, you can use (new Thread(new MyThread)).start(); to start a thread.
For detailed infomation, just refer to oracle official doc.
The MyThread instance you are passing is just acting as Runnable and not as a separate Thread.
There is basically no difference logically in both ways:
What Thread internally does on start() is, calls the run() method of Runnable.
And when you are doing new Thread(new MyThread()).start(), you are just being redundant as Thread itself implements Runnable.
But it will make no difference logically as the run() method of MyThread will be called by the new Thread.
You shouldn't do this. Creating a thread does change some variables like the "number of unstarted threads" in ThreadGroup.
While it shouldn't exactly cause problems, it's bad style and will confuse people ("Why did he do that? There must be a good reason!").
If your class itself extends Thread you can follow your first way:
MyThread myThread = new MyThread();
myThread.start();
If you look into the JavaDoc, you'll see that your second way is targeted towards classes that (just) implement Runnable (which means that your class just needs to implement run() method).
public class MyClass implements Runnable {
public void run() { ... }
}
Thread thread = new Thread(new MyClass());
thread.start();
The difference is that Runnable is only an interface whereas Thread is a class. This means that if you want to have your logic as part of a class which needs for some reason to extend a different class, then you can still implement Runnable and use the second way.
Thread itself is an implementation of Runnable. When create an instance of Thread and start it, it will executes it's own run() method. If non-null Runnable target is given to it's constructor, then it will invoke it's target's run() method as is evident from the implemented run() method of Thread class:
#Override
public void run() {
if (target != null) {
target.run();
}
}
The two ways to create a new thread of execution:
First one is to declare a class(i.e. PThread) to be a subclass of Thread: PThread extends PThread and should override the run method of class Thread. We can then easily create instantiate of this class and invoke start() on it:
PThread pThread = new PThread(args);
pThread.start();
Second one is to declare a class that implements the Runnable interface: RThread implements Runnable then implements the run method. We will have to instantiate the RThread and pass it to a Thread instance as a Runnable target:
RunThread rThread = new RunThread(args); // args constructor argument if required
Thread t = new Thread(rThread);
t.start();
As you have seen from the above way to start a thread, It is actually allowed a class extending a Thread, such as PThread to be passed to a new Thread constructor as a Runnable target to start it. Because Thread itself is an implementation of Runnable.
PThread pThread = new PThread(args);
Thread t = new Thread(pThread);
// allowed as pThread is extending Thread and hence,
//an implementation of Runnable
t.start();
But this operation is unnecessary or, rather you should not do it. As pThread is already a Thread, we could just call pThread.start() to executes it's run() method, which is the heart of a Thread. Creating another thread just to execute pThread is just extra overhead as it will not do anything other than executing pThread's run() method.
However, you should not actually use an extension of Thread at all. Because,
implementing Runnable is always preferable over extending a Thread:
Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.
Implementing Runnable to a Class still allows us to extend it to other class if necessary.
In OOP, extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread or changing it's behavior, than use Runnable interface instead.
Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.
Executors, which makes life easier with multi-threading accepts Runnable as task.
Reference:
Class Thread
Difference between Thread class and Runnable interface
(new Thread(new MyThread)).start();
each Thread implements Runnable; in this case MyThread instance is used as Runnable the new thread calls the run method implemented by MyThread. You will not be able to stop the thread ( or control it by any means) by using MyThread.
There are absolutely no difference between how you start the Thread (class implementing Runnable or extending Thread class)
It's only the abstraction that you apply, note (Runnable object, is more general, because the Runnable object can subclass a class other than Thread) Good Coding Practice.
In both of the cases Thread.start() will called

runnable future interface definition (jdk)

I have a question about the "correctness" of the RunnableFuture interface's definition. This may be a question about the correct contention for defining interfaces comments in java.
The definition of the RunnableFuture's run() method:
Sets this Future to the result of its computation ...
However, this clearly cannot be always true, since run()'s return type is void, and RunnableFuture is but an interface, it seems that if we were to gaurantee this, we would have to know something about the nature of the implementing class (the get() implementation, for example).
Now, if the RunnableFuture actually returned a value, which was hidden and always returned by an otherwise blocking get() function, such a definition (which would have to occur in a class, rather than an interface, due to its implementation restriction), would clearly be appropriate.
Thus, I am wondering: is the run() method for this interface correctly defined ?
As a counterexample: the Runnable run() interface definition is always correct.
When an object implementing interface Runnable is used to create a
thread, starting the thread causes the object's run method to be
called in that separately executing thread.
Thus, even though Runnable defines no implementation - the interface tells us how the JVM implements threads via the Runnable interface, without unnecessarily imposing non-gauranteed contract on implementing classes.
So I have 3 questions:
Is the documentation for RunnableFuture capable of being incorrect for several cases ?
If (1) is the case, is that acceptable via java conventions?
What is the "real" difference between a RunnableFuture run() and a Runnable run(), if any ?
See http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
The contract of RunnableFuture is implemented by FutureTask. When you create a FutureTask, you provide either a Callable or a Runnable and a value. The run method of FutureTask looks something like:
public void run() {
V result;
try {
if(callable) {
result = callable.call();
} else {
runnable.run();
result = value;
}
} catch (Throwable t) {
setException(t);
return;
}
set(result);
}
Except the actual implementation wraps the Runnable-value pair in a Callable and does some extra checks to ensure the FutureTask is in the correct state before run is invoked.

Categories

Resources