Add test to ensure entities are GCed

This commit is contained in:
themode 2022-03-05 17:28:48 +01:00
parent 1bea4848ac
commit bd533fc2f2
4 changed files with 35 additions and 20 deletions

View File

@ -0,0 +1,15 @@
package net.minestom.server.api;
import java.lang.ref.WeakReference;
public class TestUtils {
public static void waitUntilCleared(WeakReference<?> ref) {
while (ref.get() != null) {
System.gc();
try {
Thread.sleep(50);
} catch (InterruptedException ignore) {
}
}
}
}

View File

@ -7,9 +7,11 @@ import net.minestom.server.network.packet.server.play.DestroyEntitiesPacket;
import net.minestom.server.utils.time.TimeUnit;
import org.junit.jupiter.api.Test;
import java.lang.ref.WeakReference;
import java.time.temporal.TemporalUnit;
import java.util.List;
import static net.minestom.server.api.TestUtils.waitUntilCleared;
import static org.junit.jupiter.api.Assertions.*;
@EnvTest
@ -61,6 +63,21 @@ public class EntityRemovalIntegrationTest {
assertEquals(1, entity.getAliveTicks());
}
@Test
public void entityGC(Env env) {
// Ensure that entities do not stay in memory after they are removed
var instance = env.createFlatInstance();
var entity = new Entity(EntityType.ZOMBIE);
entity.setInstance(instance, new Pos(0, 40, 0)).join();
entity.remove();
var ref = new WeakReference<>(entity);
//noinspection UnusedAssignment
entity = null;
env.tick(); // Required to remove the entity from the thread dispatcher
waitUntilCleared(ref);
}
static final class TestEntity extends Entity {
public TestEntity(long delay, TemporalUnit unit) {
super(EntityType.ZOMBIE);

View File

@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test;
import java.lang.ref.WeakReference;
import java.util.concurrent.atomic.AtomicBoolean;
import static net.minestom.server.api.TestUtils.waitUntilCleared;
import static org.junit.jupiter.api.Assertions.*;
public class EventNodeMapTest {
@ -81,14 +82,4 @@ public class EventNodeMapTest {
item = null;
waitUntilCleared(ref);
}
private static void waitUntilCleared(WeakReference<?> ref) {
while (ref.get() != null) {
System.gc();
try {
Thread.sleep(50);
} catch (InterruptedException ignore) {
}
}
}
}

View File

@ -8,6 +8,8 @@ import org.junit.jupiter.api.Test;
import java.lang.ref.WeakReference;
import static net.minestom.server.api.TestUtils.waitUntilCleared;
@EnvTest
public class InstanceUnregisterIntegrationTest {
@ -58,14 +60,4 @@ public class InstanceUnregisterIntegrationTest {
chunk = null;
waitUntilCleared(ref);
}
private static void waitUntilCleared(WeakReference<?> ref) {
while (ref.get() != null) {
System.gc();
try {
Thread.sleep(50);
} catch (InterruptedException ignore) {
}
}
}
}