Thread Safety?

Discussion in 'Plugin Development' started by MrTwiggy, Feb 6, 2013.

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


    I was just wondering, is teleporting players and adding to lists thread safe?

    I know that removing or modifying the objects in an existing list on a seperate thread generally isn't thread safe because of concurrency issues, but it would see like adding to a list on a seperate thread wouldn't cause any issues, would it?

    The reason I ask is that I have a database of player information, that I load for the player whenever they log on. However, in order to avoid future lag issues with the main server thread while accessing the database and loading their information, I would like to create a seperate thread using the scheduler to load their information, add it to the player list, and then teleport the player.

    So, is *adding* objects to a list and teleporting players thread safe?
  2. Offline


    Teleporting players is not thread safe.

    However, you can add information to your own list by using synchronization or the ever popular ConcurrentHashMap if you need a map. These are drop-in classes that you can insert wherever you're using ArrayList or HashMap without significantly changing the code.

    Though, iterating and using "containsKey/contains" may still be unsafe. I'd recommend reading up on thread safety and the java.util.concurrent classes.
  3. Offline

    ZeusAllMighty11 Retired Staff

  4. Offline


    I'm confused. So you can't teleport people safely?
  5. Offline


    So using the synchronization, as long as I declare my arraylist as Collections.synchronizedList(newArrayList<String>()); instead of ArrayList<String>(), I can add objects to the list from a seperate thread? Or do I also need to go through every that I iterate the list and add the (synchronize){ iterate here... }?
  6. Offline

    Sagacious_Zed Bukkit Docs

    Both. As mentioned in the javadocs for synchronizedList If you need to call multiple methods that is one logical operation you need to synchronize over the list.
Thread Status:
Not open for further replies.

Share This Page