2022-03-03 07:44:57 +01:00
|
|
|
|
|
|
|
|
|
|
|
package net.minestom.server.snapshot;
|
|
|
|
|
|
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
|
2022-05-03 18:55:41 +02:00
|
|
|
import java.util.*;
|
2022-03-03 07:44:57 +01:00
|
|
|
import java.util.concurrent.atomic.AtomicReference;
|
|
|
|
|
|
|
|
final class SnapshotUpdaterImpl implements SnapshotUpdater {
|
2022-05-04 18:24:15 +02:00
|
|
|
private final IdentityHashMap<Snapshotable, AtomicReference<Snapshot>> referenceMap = new IdentityHashMap<>();
|
|
|
|
private IdentityHashMap<Snapshotable, AtomicReference<Snapshot>> readOnlyReferenceMap;
|
2022-03-03 07:44:57 +01:00
|
|
|
private List<Entry> queue = new ArrayList<>();
|
|
|
|
|
|
|
|
static <T extends Snapshot> @NotNull T update(@NotNull Snapshotable snapshotable) {
|
|
|
|
var updater = new SnapshotUpdaterImpl();
|
|
|
|
var ref = updater.reference(snapshotable);
|
|
|
|
updater.update();
|
2022-03-03 12:13:25 +01:00
|
|
|
return (T) ref.get();
|
2022-03-03 07:44:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2022-05-04 18:24:15 +02:00
|
|
|
public <T extends Snapshot> @NotNull AtomicReference<T> reference(@NotNull Snapshotable snapshotable) {
|
|
|
|
AtomicReference<Snapshot> ref;
|
|
|
|
// Very often the same snapshotable is referenced multiple times.
|
|
|
|
var readOnly = this.readOnlyReferenceMap;
|
|
|
|
if (readOnly != null && (ref = readOnly.get(snapshotable)) != null) {
|
|
|
|
return (AtomicReference<T>) ref;
|
|
|
|
}
|
|
|
|
// If this is a new snapshotable, we need to create a new reference.
|
|
|
|
synchronized (this) {
|
|
|
|
ref = new AtomicReference<>();
|
|
|
|
var prev = referenceMap.putIfAbsent(snapshotable, ref);
|
|
|
|
if (prev != null) return (AtomicReference<T>) prev;
|
|
|
|
this.queue.add(new Entry(snapshotable, ref));
|
|
|
|
return (AtomicReference<T>) ref;
|
|
|
|
}
|
2022-03-03 07:44:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
record Entry(Snapshotable snapshotable, AtomicReference<Snapshot> ref) {
|
|
|
|
}
|
|
|
|
|
|
|
|
void update() {
|
|
|
|
List<Entry> temp;
|
|
|
|
while (!(temp = new ArrayList<>(queue)).isEmpty()) {
|
|
|
|
queue = new ArrayList<>();
|
2022-05-04 18:24:15 +02:00
|
|
|
readOnlyReferenceMap = (IdentityHashMap<Snapshotable, AtomicReference<Snapshot>>) referenceMap.clone();
|
2022-03-03 07:44:57 +01:00
|
|
|
temp.parallelStream().forEach(entry -> {
|
|
|
|
Snapshotable snap = entry.snapshotable;
|
2022-03-03 12:13:25 +01:00
|
|
|
entry.ref.set(Objects.requireNonNull(snap.updateSnapshot(this), "Snapshot must not be null after an update!"));
|
2022-03-03 07:44:57 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|