Buffer collection cleaner

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2021-09-29 18:31:28 +02:00
parent 729fc14e6d
commit 36bcf69728
2 changed files with 22 additions and 8 deletions

View File

@ -85,6 +85,7 @@ public class PlayerSocketConnection extends PlayerConnection {
this.channel = channel;
this.remoteAddress = remoteAddress;
PooledBuffers.registerBuffer(this, tickBuffer);
PooledBuffers.registerBuffers(this, waitingBuffers);
}
public void processPackets(Worker.Context workerContext, PacketProcessor packetProcessor) {
@ -342,14 +343,6 @@ public class PlayerSocketConnection extends PlayerConnection {
@Override
public void disconnect() {
synchronized (bufferLock) {
if (!waitingBuffers.isEmpty()) {
for (BinaryBuffer waitingBuffer : waitingBuffers) {
PooledBuffers.add(waitingBuffer);
}
this.waitingBuffers.clear();
}
}
this.worker.disconnect(this, channel);
}

View File

@ -4,6 +4,7 @@ import org.jetbrains.annotations.ApiStatus;
import java.lang.ref.Cleaner;
import java.lang.ref.SoftReference;
import java.util.Collection;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
@ -47,6 +48,10 @@ public final class PooledBuffers {
CLEANER.register(ref, new BufferCleaner(buffer));
}
public static void registerBuffers(Object ref, Collection<BinaryBuffer> buffers) {
CLEANER.register(ref, new BuffersCleaner(buffers));
}
private static final class BufferRefCleaner implements Runnable {
private final AtomicReference<BinaryBuffer> bufferRef;
@ -72,4 +77,20 @@ public final class PooledBuffers {
add(buffer);
}
}
private static final class BuffersCleaner implements Runnable {
private final Collection<BinaryBuffer> buffers;
public BuffersCleaner(Collection<BinaryBuffer> buffers) {
this.buffers = buffers;
}
@Override
public void run() {
if (buffers.isEmpty()) return;
for (BinaryBuffer buffer : buffers) {
add(buffer);
}
}
}
}