Skip to content

Instantly share code, notes, and snippets.

@kdgregory

kdgregory/Main.java Secret

Last active Feb 25, 2021
Embed
What would you like to do?
Demonstrates the time taken for first invocation of a Java8 lambda
import java.util.function.Supplier;
/**
* An example that shows the time taken to invoke a Lambda for the first time.
*/
public class Main
{
public static void main(String[] argv)
throws Exception
{
long start = System.currentTimeMillis();
// uncomment one of these
// retryLoop(50, 250);
// retryLambda(50, 250, () -> doSomething());
long elapsed = System.currentTimeMillis() - start;
System.out.println("elapsed = " + elapsed);
}
public static String retryLoop(long interval, long timeout) throws Exception
{
long timeoutAt = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < timeoutAt)
{
String value = doSomething();
if (value != null)
return value;
Thread.sleep(interval);
}
return null;
}
public static String retryLambda(long interval, long timeout, Supplier<String> lambda) throws Exception
{
long timeoutAt = System.currentTimeMillis() + timeout;
while (System.currentTimeMillis() < timeoutAt)
{
String value = lambda.get();
if (value != null)
return value;
Thread.sleep(interval);
}
return null;
}
public static String doSomething()
{
return "it doesn't matter what I return";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment