SpigotMC/Spigot — pull request #140 by FrozenBrain (2014-03-23 01:21:11+00:00)
Title: Fix TileEntities getting ticked after being queued for removal

**Summary**
Unloading and reloading a chunk within the same tick causes two TileEntities with equal coordinates to exist and tick causing different side effects.

**Explanation**
One of our players noticed that one item he put in a hopper loop duplicated again and again after a short while. After a bit of testing I discovered that this is easily reproducible by simply unloading and reloading the chunk that contains both hoppers. Clearing the old TE's inventory before loading the chunk prevented this from happening. I could also easily proof my assumption by registering the InventoryMoveItemEvent which sometimes fired two (or more) times at the exact same tick for two different instances of TileEntityHopper at the same coordinates. This is obviously not supposed to happen but confirmed that both the old and the new TileEntity move one item to the other hopper thus duplicating the item.

**Demonstration**
https://www.youtube.com/watch?v=YnEddMLO3PA
http://pastebin.com/1jydfWNN

**The solution**
Every time [CraftWorld.unloadChunk](https://github.com/Bukkit/CraftBukkit/blob/e682ac7091ed5b7f263eaaf929a3d1045ee88d8c/src/main/java/org/bukkit/craftbukkit/CraftWorld.java#L171) is called the TileEntities inside the chunk [get queued for removal](https://github.com/Bukkit/CraftBukkit/blob/e682ac7091ed5b7f263eaaf929a3d1045ee88d8c/src/main/java/org/bukkit/craftbukkit/CraftWorld.java#L181) and the chunk is [removed directly without adding it to the chunk unload queue](https://github.com/Bukkit/CraftBukkit/blob/e682ac7091ed5b7f263eaaf929a3d1045ee88d8c/src/main/java/org/bukkit/craftbukkit/CraftWorld.java#L188). In [World.tickEntities](https://github.com/Bukkit/CraftBukkit/blob/master/src/main/java/net/minecraft/server/World.java#L1127) all TileEntities in [chunks that are not queued for removal](https://github.com/Bukkit/CraftBukkit/blob/master/src/main/java/net/minecraft/server/World.java#L1247) get ticked. But because Bukkit does not add the chunk to that queue and the old TileEntity has not yet been removed there are two TileEntities of the same block in the *tileEntityList* at this point. This PR moves [the removal of old TileEntities](https://github.com/Bukkit/CraftBukkit/blob/master/src/main/java/net/minecraft/server/World.java#L1276) so that old ones are ignored. As far as I know this does not cause any other side effects. We deployed this fix to our public server yesterday and no problems have been reported so far.