Currently I have following code responsible for one of YamlConfiguration files: Code:java private FileConfiguration RegisteredNames = null; private File RegisteredNamesFile = null; private boolean needSave = false; public void reloadRegisteredNames() { if (RegisteredNamesFile == null) { RegisteredNamesFile = new File(getDataFolder(), "RegisteredNamesData.yml"); } RegisteredNames = YamlConfiguration.loadConfiguration(RegisteredNamesFile); } public FileConfiguration getRegisteredNames() { if (RegisteredNames == null) { this.reloadRegisteredNames(); } return RegisteredNames; } public void saveRegisteredNames() { if (RegisteredNames == null || RegisteredNamesFile == null) { return; } try { getRegisteredNames().save(RegisteredNamesFile); this.getLogger().info("Database saved"); } catch (IOException ex) { this.getLogger().log(Level.SEVERE, "Could not save config to " + RegisteredNamesFile, ex); } } @Override public void onEnable(){ getServer().getPluginManager().registerEvents(this, this); reloadRegisteredNames(); Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ @Override public void run() { if(!needSave) return; saveRegisteredNames(); needSave = false; }}, 6000, 6000); } My target is moving file saving to separate thread. Will it be safe and enough to simply replace SyncRepeatingTask to AsyncRepeatingTask? Let's also take in mind that file contains extremely important information, and losing/corrupting this file can cause very bad things.
Considering the AsyncRepeatingTask is deprecated, because when working with any gameplay stuff with it there is a possibility of seriously screwing things up if it's not in sync with the main thread. And it was depriated a few versions ago I don't really know if it will work. You can easily make your own thread that does this though but make sure that anywhere that you are accessing the file in the thread that you don't attempt to access it anywhere else in your code at the same time as that can screw it up. You can just make a flag that says whether or not you are using it in the thread. Here's some simple code that will do what you are looking for in a thread: Code:java new Thread(new Runnable(){ @Override public void run() { while(true) { accessingFileFlag = true; //do whatever with file here accessingFileFlag = false; try { this.sleep(60000); //will cause this thread to sleep for 1 minute as the number is in milliseconds } catch(Exception e) { e.printStackTrace()} //This means that the thread was interrupted while it was 'sleeping' } }}).start();
rsod Yes, it's safe to save data to disk/a database off the main thread. Make sure the data is in memory and you're not getting it from the server though.