I am starting to learn how to develop with Optional
in java8. It might be it is somwehere documented, but I have been using google with no accurate result.
I have different possible implementations for the orElseGet
method, and I am not sure if java makes a better memory handling in some case, or if its pretty much the same.
Lets say I have a method in a class with an Optional
defined:
class myClass {
final static private Supplier<Object> MY_SUPPLIER = () -> new Object();
private void myMethod1 () {
Optional<Object> x; // somehow Initialized
Object y = x.orElseGet(() -> new Object());
}
private void myMethod2 () {
Optional<Object> x; // somehow Initialized
Object y = x.orElseGet(MY_SUPPLIER);
}
}
From my humble point of view, this second should have better memory management in java, since it's only declared once the Supplier
, and it is always used the same.
1) is this true?
Now, let's go further, and imagine we need to supply different object depending on parameters.
class myClass2 {
final static private Function<String, Supplier<AnyCustomClass>> MY_SUPPLIER_PROVIDER = (p) -> () -> new AnyCustomClass(p);
private void myMethod1 (String arg) {
Optional<AnyCustomClass> x; // somehow Initialized
AnyCustomClass y = x.orElseGet(() -> new AnyCustomClass(arg));
}
private void myMethod2 (String arg) {
Optional<AnyCustomClass> x; // somehow Initialized
AnyCustomClass y = x.orElseGet(MY_SUPPLIER_PROVIDER.apply(arg));
}
}
In this case, depending on the argument, each time it returns different supplier.
2) Does java have better memory management here also?
3) Do they somehow get "cached" for arg taking same value?
EDIT
By watching Does a lambda expression create an object on the heap every time it's executed? I understand that my first class behaviour is answered. Since there are no local variables, it will create a singleton (at least oracle jvm)
How ever, I do not feel like that answer provides accurate information to answer my 2) and 3)