Misc networking improvements

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2022-04-02 22:05:29 +02:00
parent 446e4a64b7
commit ff8dd0cdaa
2 changed files with 6 additions and 15 deletions

View File

@ -5,7 +5,6 @@ import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.invoke.VarHandle;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;
import java.util.function.Supplier;
@ -20,7 +19,7 @@ import java.util.function.Supplier;
@ApiStatus.Internal
public final class CachedPacket implements SendablePacket {
private final Supplier<ServerPacket> packetSupplier;
private SoftReference<FramedPacket> packet;
private volatile SoftReference<FramedPacket> packet;
public CachedPacket(@NotNull Supplier<@NotNull ServerPacket> packetSupplier) {
this.packetSupplier = packetSupplier;
@ -32,7 +31,6 @@ public final class CachedPacket implements SendablePacket {
public void invalidate() {
this.packet = null;
VarHandle.releaseFence();
}
public @NotNull ServerPacket packet() {
@ -48,13 +46,11 @@ public final class CachedPacket implements SendablePacket {
private @Nullable FramedPacket updatedCache() {
if (!PacketUtils.CACHED_PACKET)
return null;
VarHandle.acquireFence();
SoftReference<FramedPacket> ref = packet;
FramedPacket cache;
if (ref == null || (cache = ref.get()) == null) {
cache = PacketUtils.allocateTrimmedPacket(packetSupplier.get());
this.packet = new SoftReference<>(cache);
VarHandle.releaseFence();
}
return cache;
}

View File

@ -413,18 +413,13 @@ public class PlayerSocketConnection extends PlayerConnection {
}
public void flushSync() throws IOException {
final SocketChannel channel = this.channel;
final List<BinaryBuffer> waitingBuffers = this.waitingBuffers;
if (!channel.isConnected()) throw new ClosedChannelException();
// Fast exit if the tick buffer can be reused
if (waitingBuffers.isEmpty() && tickBuffer.getPlain().writeChannel(channel))
return; // Fast exit if the tick buffer can be reused
try {
updateLocalBuffer();
} catch (OutOfMemoryError e) {
this.waitingBuffers.clear();
System.gc(); // Explicit gc forcing buffers to be collected
throw new ClosedChannelException();
}
return;
// Write as much as possible from the waiting list
Iterator<BinaryBuffer> iterator = waitingBuffers.iterator();
while (iterator.hasNext()) {