Synchronize the full `reference` method

This commit is contained in:
themode 2022-03-03 18:20:32 +01:00
parent f1465804c6
commit c5d1d8bc36
1 changed files with 6 additions and 11 deletions

View File

@ -2,17 +2,16 @@
package net.minestom.server.snapshot;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
final class SnapshotUpdaterImpl implements SnapshotUpdater {
private final Map<Snapshotable, AtomicReference<Snapshot>> referenceMap = new ConcurrentHashMap<>();
private final Object2ObjectOpenHashMap<Snapshotable, AtomicReference<Snapshot>> referenceMap = new Object2ObjectOpenHashMap<>();
private List<Entry> queue = new ArrayList<>();
static <T extends Snapshot> @NotNull T update(@NotNull Snapshotable snapshotable) {
@ -23,16 +22,12 @@ final class SnapshotUpdaterImpl implements SnapshotUpdater {
}
@Override
public <T extends Snapshot> @NotNull AtomicReference<T> reference(@NotNull Snapshotable snapshotable) {
public synchronized <T extends Snapshot> @NotNull AtomicReference<T> reference(@NotNull Snapshotable snapshotable) {
AtomicReference<Snapshot> ref = new AtomicReference<>();
var prev = referenceMap.putIfAbsent(snapshotable, ref);
if (prev == null) {
synchronized (this) {
queue.add(new Entry(snapshotable, ref));
}
return (AtomicReference<T>) ref;
}
return (AtomicReference<T>) prev;
if (prev != null) return (AtomicReference<T>) prev;
this.queue.add(new Entry(snapshotable, ref));
return (AtomicReference<T>) ref;
}
record Entry(Snapshotable snapshotable, AtomicReference<Snapshot> ref) {