Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are lambda-expressions in Java8 executed multi threaded?

In Java8, lambda expressions were introduced. This question is about when parallel lambdas are executed.

Before Java8, Callable-classes were one way to execute multiple threads at one time. Callables can be used with Executor-classes to be executed. Let's assume I am using a Fixed Thread Pool, using 3 as number of active processing tasks. And let's assume I have 8 tasks. Fixed Thread Pool would start first three tasks, and as one finishes, next task is started, until all 8 tasks are finished.

What would happen, if I implement my tasks as Java8-lambdas? Would all 8 be started at once? Or sequentially? Or in any clever way?

In special, are they running in the same thread as the caller (without using an Exeuctor)? By their nature, I guess lambdas could be executed in another thread easily.

like image 426
Markus Schulte Avatar asked May 06 '14 12:05

Markus Schulte


1 Answers

Runnable r = () -> System.out.println("hello");

is equivalent to

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("hello")
    }
};

And it doesn't change anything to how a runnable is executed. If you submit your runnable to a thread pool, then the thread pool will execute it, whatever you used to create your runnable: a lambda, an anonymous class, or a top-level class. In the end, what you define is an instance of Runnable, and that's the only thing which matters.

like image 93
JB Nizet Avatar answered Nov 09 '22 18:11

JB Nizet