Multi-thread listener

Discussion in 'Plugin Development' started by NemesisMate, Sep 30, 2013.

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

    NemesisMate

    I would like to know if is there a way to make a listener work on a separated thread so TPS is not so affected for that event handlers. If so, how can I make it?.
    (It doesn't matter if it affects to synchronicity or not)
     
  2. Offline

    tommycake50

    No(It matters if it affects synchronicity).
    And i don't think there is anyway either.
     
  3. Offline

    blablubbabc

    The listener itself works on the same thread the event was called from: for example you can create new events and call these from a different thread, then your listener which listens for this event will also be execute in that different thread.

    Most bukkit events however are called from the main thread, so your listeners are also invoked in the main thread
    However, if your event handling doesn't invlove the bukkit api you can maybe move it to a seperate thread.
    Example: onPlayerJoin you want to add the player to a database:

    You listen to it regulary, but when it is called you execute your add-to-database stuff (the stuff which would otherwise slow down the main thread) into a async task.
     
    tommycake50 likes this.
  4. Offline

    1Rogue

    What is this code you are wanting to move to a different thread?
     
  5. Offline

    NemesisMate

    Ok, thanks, is not what I really want but if is the only way I'll do a workaround, but if I understood it well, if I make a new thread on an event and inside it I trigger my own custom event the listener of the custom event will work on a different thread?.
     
  6. Offline

    blablubbabc

    Theoretically, yes. However, you could also just do the following inside your listener:

    Bukkit.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {

    @Override
    public void run() {
    // this code here will be run in a different thread (make sure that it doesn't use bukkit api)
    }
    });

    Also note, that you will have to think about all the potential problems which arise from whatever you do inside that run method asynchronously, like locking or unexpected finish-order, etc..

    Example: on PlayerJoinEvent you run the code for adding the player to the database asynchronously, but in the next moment you want to read some values from the database about that player: it is then not garanteed that the first async task has yet finished / you can't be sure, if the player was yet added to the database.. so you will have to think of solutions for that too then.
     
  7. Offline

    NemesisMate


    When is said to not use Bukkit API, which elements are really dangerous to use?
     
  8. Offline

    blablubbabc

  9. Offline

    NemesisMate

Thread Status:
Not open for further replies.

Share This Page