File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
src/main/java/net/darkhax/bookshelf/lib/function Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ package net .darkhax .bookshelf .lib .function ;
2+
3+ import java .lang .ref .WeakReference ;
4+ import java .util .function .Supplier ;
5+
6+ import javax .annotation .Nullable ;
7+
8+ /**
9+ * A proxy for an object that is calculated as needed at a later point. The calculated object
10+ * will be held with a weak reference that will be regenerated as needed when the reference
11+ * expires.
12+ *
13+ * @param <T> The type of object held by the lazy weak reference.
14+ */
15+ public class LazyWeakReference <T > implements Supplier <T > {
16+
17+ /**
18+ * A supplier used to generate the value held by the weak reference. This is used when the
19+ * weak reference does not exist or the value it's referencing has been discarded.
20+ */
21+ private final Supplier <T > supplier ;
22+
23+ /**
24+ * A weak reference to the held value. This will be null until the value is first
25+ * requested.
26+ */
27+ @ Nullable
28+ private WeakReference <T > reference ;
29+
30+ public LazyWeakReference (Supplier <T > supplier ) {
31+
32+ this .supplier = supplier ;
33+ }
34+
35+ @ Override
36+ public T get () {
37+
38+ // Get the existing reference value.
39+ @ Nullable
40+ final T existing = this .reference != null ? this .reference .get () : null ;
41+
42+ // If the existing reference does not exist, create a new value and update the
43+ // reference.
44+ if (existing == null ) {
45+
46+ final T fresh = this .supplier .get ();
47+ this .reference = new WeakReference <>(fresh );
48+ return fresh ;
49+ }
50+
51+ return existing ;
52+ }
53+ }
You can’t perform that action at this time.
0 commit comments