Skip to content

Instantly share code, notes, and snippets.

@hamburghammer
Created November 7, 2019 14:27
Show Gist options
  • Save hamburghammer/c34a4914a118e5da60d86ad3f56c3420 to your computer and use it in GitHub Desktop.
Save hamburghammer/c34a4914a118e5da60d86ad3f56c3420 to your computer and use it in GitHub Desktop.
Cache stuff immutable in an Java object
public final class Foo {
private final int a;
private final int b;
//Immutabel cache even without final because it's the result of final/immutable data
private int calculateCache; //init = 0
public Foo(int a, int b) {
this.a = a;
this.b = b;
}
public int calculate() {
if(calculateCache == 0) { //check if cache is in init state
calculateCache = a * b;
}
returne calculateCache;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment