[Solved] Asynchrous file saving

Discussion in 'Spigot Plugin Development' started by Creeoer, Jul 8, 2015.

  1. Creeoer

    Supporter

    Would it be a problem if I periodically saved a file configuration asynchronously? Perhaps name a scenario that could arise?
     
  2. The saving (io) wouldnt be a problem but you have to be careful that you arent modifing the underlying map while doing so. Using bukkits config might be a little tricky because the internals arent left to you but if you write your own you could make it work for sure.
     
  3. You could do that. However, just try to keep it thread-safe. An example that could arise is if while you're saving it asynchronously, some other method in the sync thread tries to save as well or edit the FileConfiguration object. There are several ways to prevent this from happening, however.
     
  4. Creeoer

    Supporter

    The thread is created after the editing is finished and canceled after the first run, so I've already stopped that from happening.
     
  5. You should make use of synchronization
     
  6. Creeoer

    Supporter

    I don't want to sync it as saving it each time a change is made can be an impact on performance.
     
  7. You don't even need that.
    (forgive any errors, typing off memory and I use helper methods for scheduling)
    Code (Text):

    final String data = config.saveToString();
    Bukkit.getScheduler().runTaskAsync(plugin, () -> {
        // save data to file
    });
     
    This is thread safe and simple.
     
    • Like Like x 2
  8. Wow that is beautiful.
     
  9. Remember, Java 8 is needed for lamba
     
  10. Of course, but still doable just the same with a few more characters.
     
    • Agree Agree x 1