Loading a file in a async thread

Discussion in 'Plugin Development' started by randomizer1234, Apr 12, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    randomizer1234

    Hello,
    I need an advice from someone which has experience in multi-thread programming.
    I need to load a file asynchronously, and then notify somehow the main plugin class that I've loaded the file and the data is ready to be used, and also provide the data (which will be a deserialized class).

    I also have to make sure that while I load the data, I don't load the same file again (for example if the user spams the command that triggers the file loading).
    This one seems to be easy: I put in a list the files that I'm already loading and if there comes a request for one of those file I simply discard it.

    What I can't figure out is pretty much the communication between the main thread (the plugin's one) and the other threads that I will create to load the files.

    Any help is appreciated! Thank you :)
     
  2. You can create a sync task using Bukkit scheduler inside the async task to trigger stuff on the main thread, it's designed for that kind of use.
     
  3. Offline

    randomizer1234

    Right! Thank you, that was the missing bit of the solution in my head :)
     
  4. Offline

    macguy8

    randomizer1234

    To put what Digi said into more readable code...

    Code:
    //pseudo code
    create a new thread:
       Do stuff in the thread.
       When the stuff is done, use Bukkit.getScheduler().scheduleSyncDelayedTask(new Runnable() {
           //Contact your plugin here, this is now a sync task, so it's safe to use bukkit methods.
      }, plugin).
    
    Note, there is no 20L, or any time in this one. The plugin variable is an instance of your plugin - Either pass it to the new thread, or get it from Bukkit (Bukkit.getPluginManager().getPlugin(String name))

    EDIT: Ninja'd from the OP
     
  5. Offline

    randomizer1234

Thread Status:
Not open for further replies.

Share This Page