Async tasks causing TPS drops and massive CPU usage

I have a minigame designed to mirror the Minecraft battle minigame from console edition. For each game that I play after it ends the CPU usage increases and never comes back down. Once the usage hits 99% it will start causing TPS drops. I sorta know what's causing this. The method I use to generate random items for the chests around the map uses a lot of logic and random numbers so I run this using Bukkit's runTaskAsynchronously method.

schedulerIdList.add(Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> addRandomItems(chest)).getTaskId());


I add the task ID to a list so that when the game is over it can iterate over all the task IDs to cancel them.

schedulerIdList.forEach(id -> Bukkit.getScheduler().cancelTask(id));
schedulerIdList.clear();


Sometimes I get this error (or a few of them) in the console though:

Nag author(s): '[Mike]' of 'DevPlugin v1.0-SNAPSHOT' about the following: This plugin is not properly shutting down its async tasks when it is being shut down. This task may throw errors during the final shutdown logs and might not complete before process dies.

I've noticed that rarely the addRandomItems(chest) method is never even ran. I'd be happy to provide additional code if needed and I really appreciate any help because I've been stuck on this for a while now. I'm on paperMC 1.20.1
Was this page helpful?