Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MinecraftForge
GitHub Repository: MinecraftForge/MinecraftForge
Path: blob/1.21.x/src/main/java/net/minecraftforge/common/util/ClearableLazy.java
7542 views
1
/*
2
* Copyright (c) Forge Development LLC and contributors
3
* SPDX-License-Identifier: LGPL-2.1-only
4
*/
5
6
package net.minecraftforge.common.util;
7
8
9
import org.jetbrains.annotations.NotNull;
10
import org.jetbrains.annotations.Nullable;
11
12
import java.util.function.Supplier;
13
14
public interface ClearableLazy<T> extends Lazy<T> {
15
void invalidate();
16
17
/**
18
* Constructs a lazy-initialized object
19
* @param supplier The supplier for the value, to be called the first time the value is needed.
20
*/
21
static <T> ClearableLazy<T> of(@NotNull Supplier<T> supplier) {
22
return new ClearableLazy.Fast<T>(supplier);
23
}
24
25
/**
26
* Constructs a thread-safe lazy-initialized object
27
* @param supplier The supplier for the value, to be called the first time the value is needed.
28
*/
29
static <T> ClearableLazy<T> concurrentOf(@NotNull Supplier<T> supplier) {
30
return new ClearableLazy.Concurrent<>(supplier);
31
}
32
33
/**
34
* Non-thread-safe implementation.
35
*/
36
final class Fast<T> implements ClearableLazy<T> {
37
private final Supplier<T> supplier;
38
private T instance;
39
40
private Fast(Supplier<T> supplier) {
41
this.supplier = supplier;
42
}
43
44
@Nullable
45
@Override
46
public final T get() {
47
if (instance == null) {
48
instance = supplier.get();
49
}
50
return instance;
51
}
52
53
@Override
54
public void invalidate() {
55
this.instance = null;
56
}
57
}
58
59
/**
60
* Thread-safe implementation.
61
*/
62
final class Concurrent<T> implements ClearableLazy<T> {
63
private final Object lock = new Object();
64
private final Supplier<T> supplier;
65
private volatile T instance;
66
67
private Concurrent(Supplier<T> supplier) {
68
this.supplier = supplier;
69
}
70
71
@Nullable
72
@Override
73
public final T get()
74
{
75
var ret = instance;
76
if (ret == null) {
77
synchronized (lock) {
78
if (instance == null) {
79
return instance = supplier.get();
80
}
81
}
82
}
83
return ret;
84
}
85
86
@Override
87
public void invalidate() {
88
synchronized (lock) {
89
this.instance = null;
90
}
91
}
92
}
93
}
94
95