Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing lambda to a Timer instead of TimerTask [duplicate]

I want to perform a delayed operation on a map, so I am using Timer, to which I am passing a TimerTask and a delay in milliseconds:

timer.schedule(new TimerTask() {     public void run() {         tournaments.remove(id);     } }, delay); 

This is some sort of primitive cache-like functionality where I set an expiration time on a new resource that was just created.

I thought I could do that using lambdas, just like follows:

times.schedule(() -> tournaments.remove(id), delay); 

But the compiler says this cannot be done. Why? What am I doing wrong? Could I use lambdas to achieve more concise code or it's simply not possible here and I should stick to an anonymous class?

like image 535
dabadaba Avatar asked Jun 22 '16 14:06

dabadaba


People also ask

What is the relationship between timer and TimerTask?

Timer provides method to schedule Task where the task is an instance of TimerTask class, which implements the Runnable interface and overrides run() method to define task which is called on scheduled time.

Is lambda function faster than for loop?

The answer is it depends. I have seen cases where using a lambda was slower and where it was faster. I have also seen that with newer updates you get more optimal code.

Can we use lambda expression for abstract class?

Java 8 Lambda Expression can create a method argument or consider the entire code as data. It can implement a function that does not have any specific class, which means an abstract class.


1 Answers

TimerTask is not a SAM (single abstract method) type -- now, that sounds contradictory, because there is only one abstract method on TimerTask! But because the abstract parent class implements cancel and scheduledExecutionTime, even though they're not abstract, the compiler can't go so far as to take your lambda and create an anonymous subtype of TimerTask.

What can be done is lambdas for interfaces that have a single abstract method and one or more default methods, but sadly TimerTask is an older class and doesn't use the default method capabilities of Java 8.

like image 94
Thorn G Avatar answered Sep 17 '22 19:09

Thorn G