Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created March 21, 2023 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasdarimont/c12a35cf3108759ccb4cffd72ab5f8c9 to your computer and use it in GitHub Desktop.
Save thomasdarimont/c12a35cf3108759ccb4cffd72ab5f8c9 to your computer and use it in GitHub Desktop.
Instance Once
package demo;
public class InstanceOnceDemo {
public static void main(String[] args) {
var c1 = new MyClass(2);
System.out.println(c1.calc());
System.out.println(c1.calc());
var c2 = new MyClass(3);
System.out.println(c2.calc());
System.out.println(c2.calc());
}
static class MyClass {
private final int seed;
private final ClassValue<Integer> cache;
public MyClass(int seed) {
this.seed = seed;
this.cache = new ClassValue<>() {
@Override
protected Integer computeValue(Class<?> type) {
return compute();
}
};
}
public int calc() {
return this.cache.get(MyClass.class);
}
private int compute() {
System.out.println("Compute");
return 42 * seed;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment