Supplier memoization

By | March 10, 2017
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Below code is a simple way for memoization:

private String value;

public String getValue() {
    if (value == null) {
        value = "abcd";
    }
    return value;
}

This can be also wrote in Guava way:

Supplier<String> memo = Suppliers.memoize(() -> {
    return "abcd";  // inside function
});
System.out.println(memo.get());  // will call the function
System.out.println(memo.get());  // will not call the function, directly get from cache.