Player == Player for thread synchronization?

Discussion in 'Plugin Development' started by cakenggt, Jul 21, 2014.

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

    cakenggt

    Hello all,

    I am currently coding a plugin which will use multiple Async threads. Sometimes certain attributes of a player may need to be changed by multiple threads. Would it be safe to synchronize these changes to the Player instance gotten from an event such as PlayerInteractEvent?

    What I mean is, if I create a thread which holds a reference to Player A gotten from event.getPlayer(), and then synchronize certain functions on that instance, will it also be safe to create another thread in the future which holds a reference to Player A gotten from a future event.getPlayer()? Will those two player references synchronize with each other?
     
  2. Offline

    xTrollxDudex

    cakenggt
    Yes. Unless you schedule a sync task to do it for you, make sure you synchronize the correct object.
     
  3. Offline

    cakenggt

    xTrollxDudex

    Thanks a lot for answering this for me and for posterity.
     
  4. Offline

    Traks

    I don't quite understand what you mean by "synchronizing certain functions on a Player instance". Invoking methods on Player objects isn't thread safe and should never be done asynchronously, unless the underlying fields are immutable.
     
  5. Offline

    cakenggt

    Traks
    I meant using the player instance as the synchronization lock.
     
  6. Offline

    Traks

    Lock for what? Invoking methods on the Player object? That would still be thread unsafe
     
  7. Offline

    cakenggt

    Traks
    Then is the only way to be thread safe to use Bukkit.getScheduler().scheduleSyncRepeatingTask() ?
     
  8. Offline

    Traks

    Or BukkitScheduler#scheduleSyncDelayedTask (both of them). You could also create a new BukkitRunnable and invoke one of the methods on it, that would run it synchronously with the main thread. I also think this thread would answer your question a bit more in-depth :)
     
  9. Offline

    cakenggt

    Traks
    Thanks a lot!

    For posterity, I decided to go with using a BukkitRunnable because it can schedule itself repeating and cancel itself.
     
Thread Status:
Not open for further replies.

Share This Page