Search code examples
javalambdafunctional-interfacefunctional-java

How can I make use of the Lambda expression returned by spinServerUp() method in following code


I'm learning Java at the moment and I see some code that looks like this:

public interface Await {
    boolean await(long timeout, TimeUnit timeUnit) throws InterruptedException;
}
public Await spinServerUp() {
    this.startServers()
    return (timeout, timeUnit) -> countDownLatch.await(timeout, timeUnit);
}

Now, I understand that countDownLatch waits for the threads to complete before continuing on.

My question is - how do parameters timeout and timeunit get passed to the Lambda expression? I can't find any usage examples on my end for this block of code that I'm reading, so I'm a bit confused.

I'm also not sure if I follow the spinServerUp() method that well, I understand that it calls this.startServers() then returns the Lambda expression - thus giving control to the Lambda expression. Why return the Lambda expression, though?

I've tried to do some research and reading, but I got more confused. Any clarifications would be appreciated


Solution

  • how do parameters timeout and timeunit get passed to the Lambda expression?

    Just treat the returnValue as a function. Basically same as function you declared in class:

    Await await = spinServerUp();
    await.await(3, TimeUnit.SECONDS);
    

    Why return the Lambda expression though?

    Lambda function declaration does nothing util you call it like code snippet above.

    The typical usage of lambda is callback. It is something that will happen if certain event is triggered (e.g. mouse clicked on a button). So it will not do anything if certain event is not triggered.

    Or for a real world example. Jack told Nick to [call him] if Bob arrived. Call Jack is the lambda in this case and it will only be triggered if Bob arrived.

    public ThingsToDo planForBobArriving() {
      String personToCall = "Jack";
      return () -> call(personToCall); 
    }
    
    public void mainLogic() {
      ThingsToDo thingsToDoWhenBobArrived = planForBobArriving();
      while(keepWaiting) {
        if (bobArrived()) {
           thingsToDoWhenBobArrived.execute(); // call Jack
           break;
        }
      }
    }