Synchronization question

Discussion in 'Plugin Development' started by Prozza, Jul 20, 2014.

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

    Prozza

    Hey Bukkit,

    I have a question about synchronization.

    Is it possible to use block synchronization to use non-threadsafe methods in asynchronously executed code.

    For example:
    Code:java
    1.  
    2. public void playerTest() { // Sync
    3.  
    4. final Player player = Bukkit.getServer().getOnlinePlayers()[0];
    5.  
    6. new BukkitRunnable() { // Async
    7. @Override
    8. public void run() {
    9.  
    10. // Is this allowed?
    11. synchronized (Bukkit.getServer()) {
    12. player.sendMessage("Test");
    13. }
    14.  
    15. // Is this allowed?
    16. synchronizedMethodCall(player);
    17.  
    18. }
    19. }.runTaskAsynchronously(plugin);
    20. }
    21.  
    22. public synchronized void synchronizedMethodCall(Player player) {
    23. player.sendMessage("test");
    24. }
    25.  


    Would those two asynchronous accesses be allowed?
     
  2. Offline

    fireblast709

    Prozza no, sadly enough you cannot synchronize external libraries like that since it doesn't synchronize access from third parties (other plugins, MC)
     
  3. Offline

    Traks

    Your first example only suspends execution of other synchronized calls to the object returned by Bukkit#getServer(). So methods that aren't synchronized don't have to wait until the object's or class' lock has been released.

    Your second one only acquires the lock of the object it is in, but not the lock of the Player object it invokes a method on. Other threads can still invoke Player#sendMessage(String) on that Player object at the exact same moment as you.

    It is not possible to use synchronized to block access to non-synchronized methods.
     
Thread Status:
Not open for further replies.

Share This Page