[
https://issues.apache.org/jira/browse/SLING-10502?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17366583#comment-17366583
]
Julian Sedding commented on SLING-10502:
----------------------------------------
[~bdelacretaz] +1 for a utility - I would even consider adding it to Sling API
as it is very generic and often useful.
My take looks as follows:
{code:java}
public class Memoizer<T> implements Supplier<T> {
private volatile Supplier<T> computation;
private T result = null;
public static <T> Supplier<T> memoize(Supplier<T> computation) {
return new Memoizer<>(computation);
}
private Memoizer(Supplier<T> computation) {
this.computation = computation;
}
@Override
public T get() {
if (computation != null) {
synchronized (this) {
if (computation != null) {
result = computation.get();
computation = null;
}
}
}
return result;
}
}
{code}
It uses the same approach, but has some subtle differences:
- correctly use double-checked locking (volatile field is required unless I'm
missing something)
- supports {{null}} values
- minor optimization: sets {{computation = null}} once it is called
- implements {{Supplier}}
- uses static factory method instead of constructor (syntactic sugar)
Thus your example would become the following:
{code:java}
class LazyLoadingPojo {
Supplier<Integer> count = memoize(this::computeCount);
...
}
{code}
A map-based approach could be complementary. {{Map#computeIfAbsent}} could be
useful, as it has similar semantics already.
> Helpers for lazy loading of GraphQL query results
> -------------------------------------------------
>
> Key: SLING-10502
> URL: https://issues.apache.org/jira/browse/SLING-10502
> Project: Sling
> Issue Type: Improvement
> Components: GraphQL
> Affects Versions: GraphQL Core 0.0.10
> Reporter: Bertrand Delacretaz
> Priority: Minor
>
> Lazy loading of "expensive" field values can help the performance of GraphQL
> queries, by omitting calls to methods that retrieve or compute data if the
> corresponding fields are not used in the result set.
> A natural way of doing that is to return a {{Supplier<SomeType>}} instead of
> {{SomeType}} directly. I'm not sure if the GraphQL Core supports that
> correctly out of the box, it would be good to try that and maybe implement
> the corresponding improvements.
--
This message was sent by Atlassian Jira
(v8.3.4#803005)