clearing or set null to objects in java

前端 未结 7 1625
盖世英雄少女心
盖世英雄少女心 2020-12-09 09:18

I was recently looking into freeing up memory occupied by Java objects. While doing that I got confused about how objects are copied (shallow/deep) in Java and how to avoid

相关标签:
7条回答
  • 2020-12-09 09:56

    If you put the list into a hash map, the hash map now holds a reference to the list.

    If you pass the list as an argument to a method, the method will have a reference to it for the duration of the method.

    If you pass it to a thread to be manipulated, the thread will have a reference to the object until it terminates.

    In all of these cases, if you set list = null, the references will still be maintained, but they will disappear after these references disappear.

    If you simply clear the list, the references will still be valid, but will now point to a list that has suddenly been emptied, by means that may be unknown to the programmer and may be considered a bug, especially if you use the thread.

    0 讨论(0)
提交回复
热议问题