From b79054f8e8038271edc28316d228b86bb4cfe778 Mon Sep 17 00:00:00 2001 From: themode Date: Sat, 1 Jan 2022 03:54:37 +0100 Subject: [PATCH] Opaque ordering for LazyPacket --- .../network/packet/server/CachedPacket.java | 1 + .../network/packet/server/LazyPacket.java | 20 ++++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java index acee31c79..750340b33 100644 --- a/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/CachedPacket.java @@ -31,6 +31,7 @@ public final class CachedPacket implements SendablePacket { } private final Supplier packetSupplier; + @SuppressWarnings("unused") private SoftReference packet; public CachedPacket(@NotNull Supplier<@NotNull ServerPacket> packetSupplier) { diff --git a/src/main/java/net/minestom/server/network/packet/server/LazyPacket.java b/src/main/java/net/minestom/server/network/packet/server/LazyPacket.java index 4f924bda7..d5b07c4ed 100644 --- a/src/main/java/net/minestom/server/network/packet/server/LazyPacket.java +++ b/src/main/java/net/minestom/server/network/packet/server/LazyPacket.java @@ -3,6 +3,8 @@ package net.minestom.server.network.packet.server; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; import java.util.function.Supplier; /** @@ -12,20 +14,32 @@ import java.util.function.Supplier; */ @ApiStatus.Internal public final class LazyPacket implements SendablePacket { + private static final VarHandle PACKET; + + static { + try { + PACKET = MethodHandles.lookup().findVarHandle(LazyPacket.class, "packet", ServerPacket.class); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + private final Supplier packetSupplier; - private volatile ServerPacket packet; + @SuppressWarnings("unused") + private ServerPacket packet; public LazyPacket(@NotNull Supplier<@NotNull ServerPacket> packetSupplier) { this.packetSupplier = packetSupplier; } public @NotNull ServerPacket packet() { - ServerPacket packet = this.packet; + ServerPacket packet = (ServerPacket) PACKET.getOpaque(this); if (packet == null) { synchronized (this) { packet = this.packet; if (packet == null) { - packet = this.packet = packetSupplier.get(); + packet = packetSupplier.get(); + PACKET.setOpaque(this, packet); } } }