Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of ()->System.out.println("done")?

In Concurrency Interest link, there is a code which is like this:-

exec.schedule( ()-> System.out.println("done"),
         1, TimeUnit.SECONDS );

What is the meaning of ()-> ?

I checked in eclipse, it does not allow. But what was the intention of the thread-writer?

like image 782
a3.14_Infinity Avatar asked Feb 05 '14 19:02

a3.14_Infinity


2 Answers

This is Lambda syntax from JDK8.

It is pretty similar (but not exactly same) to

exec.schedule(new Runnable() { 
    public void run() {
        System.out.println("done");
    }
}, 1, TimeUnit.SECONDS);
like image 195
Sergey Grinev Avatar answered Sep 27 '22 20:09

Sergey Grinev


That is the Java 8 syntax for Lambda Expressions.

The ScheduledThreadPoolExecutor#exec(..) method expects a Runnable argument. Runnable is a functional interface because it only contains one abstract method. As such, the compiler can infer that you are defining a new Runnable instance with the lambda.

The parts between () are the run() method's parameters, ie. none. The part after the -> is the body of the method.

like image 26
Sotirios Delimanolis Avatar answered Sep 27 '22 21:09

Sotirios Delimanolis