Trail Mix

Trail Mix

2M Downloads

[1.16.3] Race condition crash with dispenser behaviors

TelepathicGrunt opened this issue ยท 0 comments

commented

I was shown this crash by another user and from what it seems, trailmix is crashing when adding dispenser behaviors.

Log:
https://paste.ee/p/Kq7sp

The code:

@SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event)
{
DispenserBlock.registerDispenseBehavior(TrailMix.Items.LAUNCHER_TMPP.get(), new DispenseLauncherBehavior(event.getServer()));
DispenserBlock.registerDispenseBehavior(TrailMix.Items.LAUNCHER_NYAN.get(), new DispenseLauncherBehavior(event.getServer()));
}

The reason it is crashing is because the dispenser map of items to behaviors is not synchronized which means it is not concurrency safe. If another mod adds or manipulates the map at the exact same time as your code, the game crashes. The really tricky thing is it is a race condition and sometimes, it crashes inconsistently.

The solution is actually super simple, event.enqueueWork. enqueueWork will make sure the code inside is ran when no other mod's code is running which makes it threadsafe again. Here's an example from my mod that you can check out.
https://github.com/TelepathicGrunt/Bumblezone/blob/9c6f905a6b27716223974e403f99a17e757e36d8/src/main/java/com/telepathicgrunt/the_bumblezone/Bumblezone.java#L114-L125

I hope this helps!