package me.nallar.tickthreading.minecraft;

import java.util.HashSet;
import java.util.Set;

import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.profiler.Profiler;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;

public class ChunkGarbageCollector {
	public static Profiler profiler = MinecraftServer.getServer().theProfiler;

	public static void garbageCollect(WorldServer worldServer) {
		profiler.startSection("chunkGC");
		int viewDistance = MinecraftServer.getServer().getConfigurationManager().getViewDistance();
		ChunkProviderServer chunkProvider = worldServer.theChunkProviderServer;
		Set<Long> chunksToUnload = new HashSet<Long>();
		for (Chunk chunk : chunkProvider.getLoadedChunks()) {
			chunksToUnload.add(ChunkCoordIntPair.chunkXZ2Int(chunk.xPosition, chunk.zPosition));
		}

		for (Object player_ : worldServer.playerEntities) {
			EntityPlayerMP player = (EntityPlayerMP) player_;
			int cX = (int) player.managedPosX >> 4;
			int cZ = (int) player.managedPosZ >> 4;
			int minX = cX - viewDistance;
			int maxX = cX + viewDistance;
			int minZ = cZ - viewDistance;
			int maxZ = cZ + viewDistance;
			for (int x = minX; x <= maxX; x++) {
				for (int z = minZ; z <= maxZ; z++) {
					chunksToUnload.remove(ChunkCoordIntPair.chunkXZ2Int(x, z));
				}
			}
		}

		chunkProvider.getChunksToUnloadSet().addAll(chunksToUnload);
		profiler.endSection();
	}
}

@@ -452,16 +452,271 @@
 ctor %7B%0D%0A
+%09public static final boolean enabled = supportsGC();%0D%0A%0D%0A%09private static boolean supportsGC() %7B%0D%0A%09%09try %7B%0D%0A%09%09%09Class.forName(%22org.bukkit.craftbukkit.util.WatchdogThread%22);%0D%0A%09%09%7D catch (ClassNotFoundException e) %7B%0D%0A%09%09%09return true;%0D%0A%09%09%7D%0D%0A%09%09return false;%0D%0A%09%7D%0D%0A%0D%0A
 %09public 
@@ -849,16 +849,52 @@
 ver) %7B%0D%0A
+%09%09if (!enabled) %7B%0D%0A%09%09%09return;%0D%0A%09%09%7D%0D%0A
 %09%09profil

Disable chunk GC under Spigot