Solved ArrayList of players

Discussion in 'Plugin Development' started by Side8StarLite, Jul 19, 2017.

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

    Side8StarLite

    Hello!
    This is mostly a general question for good programming practices.
    I've seen bukkit programmers frown upon the storing of player instances in an arraylist, saying it causes memory leaks, and instead store uuids. I have a few questions pertaining to this:
    1 - does the same rule apply to storing player instances in hashmaps? (player as key)
    2 - does the same rule apply to storing objects in an arraylist that stores player instances? (Say, an arraylist of Weapon instances which contain Player owners)
    3 - does the same rule apply to bukkit tasks, wherein a player instance might disconnect before a bukkit task is finished being completed?
    Thank you for any answers!
     
  2. Offline

    Machine Maker

    @Side8StarLite
    1. Yes I believe it does. Using a hashmap is still storing all the player info stored in the Player object.

    2. In that case, the Weapon instance does hold the Player info as well so the above would apply.

    3. I would check the PlayerQuitEvent and see if the player has an task that might cause errors if he left and cancel the task.

    Hope this helps!
     
  3. @Side8StarLite
    Yes, yes, and yes.

    If you hold on to the player reference, it can't be unloaded by the JVM, which only garbage collects when nothing is holding on to the object (okay, WeakReferences don't count), so if a player leaves while you are still holding on to that object, it can't be garbage collected, and if you're unlucky, you might prevent chunks and the world from unloading too.

    Another thing to be careful of is anonymous subclasses, which also have this problem. If you just reference a player object in the outer class from an anonymous subclass, a field in the anonymous subclass will automatically be created, and then you go back to the same problem as before. (Okay, if it's a task that runs a tick later, then it doesn't make a huge difference, but you should still be mindful of it).
     
  4. Offline

    Side8StarLite

    @X1machinemaker1X @AlvinB
    Thank you for the replies! Oh so I see, anything that holds a player instance runs a risk of memory leaks... Ok I understand
     
  5. @Side8StarLite
    Yes, only exception is if you were to use a WeakReference (or perhaps a WeakHashMap).
     
  6. Offline

    Iran

    The reason most people say not to sure the player object in a list or map is because most people don't remove them correctly after they are done using it which leads to memory leaks. Also in most cases you only need a way to determine who is in the list so storing the UUID is the best way of doing that.
     
Thread Status:
Not open for further replies.

Share This Page