Executing a code asynchronously
We can improve the Warper
plugin even more by writing its data to file asynchronously. This will help keep the main thread of the server running smoothly and lag free.
Look at the current save
method. We add the data to a YamlConfiguration
and then write the configuration to the file. Not all of this method can be run asynchronously. Adding the data to the configuration must be done synchronously to ensure that it is not modified while it is being added. However, the save
method call on the configuration may be called asynchronously. We will place the entire try/catch
block within a new BukkitRunnable
. We will then run it as a task asynchronously. This task will be stored as a static variable in the Warper
class. This is shown in the following code:
BukkitRunnable saveRunnable = new BukkitRunnable() { @Override public void run() { try { //Write the configuration to our save file config.save(new File(plugin.getDataFolder(), "warps.yml"));...