Use a lock + weak map

This commit is contained in:
TheMode 2021-08-25 17:25:08 +02:00
parent e185bca468
commit 73f125763c

View File

@ -233,7 +233,7 @@ public final class PacketUtils {
} }
} }
private static final Map<Viewable, ViewableStorage> VIEWABLE_STORAGE_MAP = new ConcurrentHashMap<>(); private static final Map<Viewable, ViewableStorage> VIEWABLE_STORAGE_MAP = new WeakHashMap<>();
private static final class ViewableStorage { private static final class ViewableStorage {
private final Viewable viewable; private final Viewable viewable;
@ -257,9 +257,7 @@ public final class PacketUtils {
} }
private synchronized void process() { private synchronized void process() {
final Set<Player> viewers = viewable.getViewers(); for (Player player : viewable.getViewers()) {
if (viewers.isEmpty()) return;
for (Player player : viewers) {
PlayerConnection connection = player.getPlayerConnection(); PlayerConnection connection = player.getPlayerConnection();
Consumer<ByteBuffer> writer = connection instanceof PlayerSocketConnection Consumer<ByteBuffer> writer = connection instanceof PlayerSocketConnection
? ((PlayerSocketConnection) connection)::write : ? ((PlayerSocketConnection) connection)::write :
@ -294,6 +292,8 @@ public final class PacketUtils {
} }
} }
private static final Object VIEWABLE_PACKET_LOCK = new Object();
public static void prepareViewablePacket(@NotNull Viewable viewable, @NotNull ServerPacket serverPacket, public static void prepareViewablePacket(@NotNull Viewable viewable, @NotNull ServerPacket serverPacket,
@Nullable Player player) { @Nullable Player player) {
if (player != null && !player.isAutoViewable()) { if (player != null && !player.isAutoViewable()) {
@ -302,18 +302,21 @@ public final class PacketUtils {
return; return;
} }
final PlayerConnection playerConnection = player != null ? player.getPlayerConnection() : null; final PlayerConnection playerConnection = player != null ? player.getPlayerConnection() : null;
ViewableStorage viewableStorage = VIEWABLE_STORAGE_MAP.computeIfAbsent(viewable, c -> new ViewableStorage(viewable)); synchronized (VIEWABLE_PACKET_LOCK) {
ViewableStorage viewableStorage = VIEWABLE_STORAGE_MAP.computeIfAbsent(viewable, ViewableStorage::new);
viewableStorage.append(playerConnection, serverPacket); viewableStorage.append(playerConnection, serverPacket);
} }
}
public static void prepareViewablePacket(@NotNull Viewable viewable, @NotNull ServerPacket serverPacket) { public static void prepareViewablePacket(@NotNull Viewable viewable, @NotNull ServerPacket serverPacket) {
prepareViewablePacket(viewable, serverPacket, null); prepareViewablePacket(viewable, serverPacket, null);
} }
public static void flush() { public static void flush() {
// TODO clear map synchronized (VIEWABLE_PACKET_LOCK) {
for (ViewableStorage viewableStorage : VIEWABLE_STORAGE_MAP.values()) { for (ViewableStorage viewableStorage : VIEWABLE_STORAGE_MAP.values()) {
viewableStorage.process(); viewableStorage.process();
} }
} }
} }
}