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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With