February 10, 2019

Using java lambda to provide implementation for Runnable interface.

There are many ways to create a thread. One of those ways is implementin Runnable interface. Again there are several ways to provide an implementation for it. One of those ways is, using lambda to provide an implementation.

If you don’t know anything about lambda, then you can read it here.

You are gonna need java 8 or above to run the programs in this article. I will keep everything very short and simple.

The simplest implementation is – that does nothing.

Runnable run = () -> {};

The above is an implementation that does nothing. Because, that implementation has empty body.

Now, we should look at an implementation, which does something. At least print a string.

Runnable printName = () -> System.out.println("Anurag");

The above code will print my first-name. That’s not enough, because it hardly does anything.

And one of advice is not to put huge code blocks in a lambda. Because, it is less readable. And it really creates problem, while debugging. I won’t recommend it at all.

Look, in real life, we either create one line lambda or we use method reference to create a lambda.

Runnable is  a Functional Interface. It has only one abstract interface. That abstract method is called run().

In our next implementation we will print the name of current thread, like we did it using a class.

Runnable runLambda = () -> System.out.println("Lambda Name :- " + Thread.currentThread().getName());

We can pass it  in a Thread costructor to run it.

Thread useLambda = new Thread(runLambda);
useLambda.setName("Lambda Inside");

The above code will print Lambda Name :- Lambda Inside.

I won’t recommend using a lambda for any serious implementation. But, it is good to know the way to use a lambda. My suggestion is to put the code in a method and use method reference to provide an implementation.