Shynixn / MCCoroutine

MCCoroutine is a library, which adds extensive support for Kotlin Coroutines for Minecraft Server environments.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Folia: Add a new dispatcher called plugin.mainDispatcher

Shynixn opened this issue · comments

As Folia does not provide any "main" minecraft thread, it becomes difficult how to handle threading in Folia based plugins.
Of course, you could handle all things asynchronously but sometimes you have to make sure only 1 thread is accessing a resource at a time.
For example, for minigame plugins you may have a list of List<Arena> containing the meta data of your created arenas and a List<Game> containing the active running games on your. You could convert all those collections to concurrency save collections but there may be even more cases where you have to make sure to synchronize access.

There is the globalRegionDispatcher which could be used for that but then all optimizations of folia may get lost again if all plugins perform most of their work on it. MCCoroutine proposes that each plugin gets their own "main thread" and corresponding "mainDispatcher" for the plugins. It is intended to execute all the stuff the plugin is going to do and send it to the corresponding region thread when the actual minecraft worlds needs to be manipulated.

Example:

plugin.launch(plugin.mainDispatcher) {
   val game = getGameByName("myfirstgame")
   game.join(player)
   
  withContext(plugin.entityDispatcher(player)) {
      player.teleport(game.lobbySpawnpoint)
      player.sendMessage("You have joined the game")
  }

   if(game.hasEnoughPlayers()){
       game.start()
   }
}

This will be the default parameter in Folia going forward. So simply calling plugin.launch {} schedules something on the "plugin main thread."