Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created September 23, 2021 09:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasdarimont/4df062ede9e61363200ac8fcfed80d80 to your computer and use it in GitHub Desktop.
Save thomasdarimont/4df062ede9e61363200ac8fcfed80d80 to your computer and use it in GitHub Desktop.
Go's sync.Once with Java 17
package wb.java17;
import java.util.function.Supplier;
public class LocalOnceDemo {
public static void main(String[] args) {
System.out.println(answer());
System.out.println(answer());
}
static int answer() {
class Once {
private static Supplier<?> compute;
static class Inner { private static final Object theAnswer = compute.get(); }
public static <T> T Do(Supplier<T> compute, Class<T> clazz) {
Once.compute = compute;
return clazz.cast(Inner.theAnswer);
}
}
return Once.Do(LocalOnceDemo::compute, Integer.class);
}
static int compute() {
System.out.println("compute");
return 42;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment