Skip to content

Commit 892ce04

Browse files
committed
Added a LazyWeakReference class which creates a lazy supplier that holds a weak reference to the computed value.
1 parent 337f5af commit 892ce04

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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+
}

0 commit comments

Comments
 (0)