Created
September 23, 2021 09:36
-
-
Save thomasdarimont/4df062ede9e61363200ac8fcfed80d80 to your computer and use it in GitHub Desktop.
Go's sync.Once with Java 17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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