lucasdc
lucasdc

Reputation: 1042

JAVA - Should I set null to every instanciated object after using it?

I have a doubt about Java Garbage Collector. Just to illustrate, I have a json like this:

List<Test_DTO> testes = new ArrayList();
JSONArray list = new JSONArray();

for (Test_DTO test : testes) {
    JSONObject obj = new JSONObject();

    if(test != null) 
        obj.put("codigo",""+test .getCodigo());

    list.put(obj);
}

list = null; 

Am I supposed to set list = null in the end of my file so that the Collector can "clean" it out? If so, should I set obj = null inside the for after list.put(obj);? Or does (the cleaning) happen automatically? This question is not specific to this example, as I said, it was just to make it clearer to understand.

Thanks in advance,

Lucas.

Upvotes: 1

Views: 185

Answers (4)

sergiu
sergiu

Reputation: 389

There's no need to set it to null. The garbage collector will take care of it. Take a look here for better understanding. http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Upvotes: 3

Shyam
Shyam

Reputation: 6444

When creating bitmaps, Android often fails with out of memory errors, and does not try to garbage collect first. Hence, call System.gc(), and you have enough memory to create Bitmaps.

If creating Objects, I think System.gc will be called automatically if needed, but not for creating bitmaps. It just fails.

So I recommend manually calling System.gc() before creating bitmaps.

Upvotes: 0

m-szalik
m-szalik

Reputation: 3654

It depends on the context.

If the code you pasted is for example a part of loop in thread that runs once per hour or a long living object's property than it is good to set null to the list reference and allow GC to trash JSONArray.

But in most cases you do not have to worry about it.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074295

Am I supposed to set list = null in the end of my file so that the Collector can "clean" it out?

There's no need provided the code you've quoted is in a method and list is a local variable within the method. When the method returns, the local variables are destroyed, and if nothing else has a reference to the object(s) those variables referred to, the objects become available for garbage collection.

If list isn't a local variable within a method, it probably should be. :-)

Note, though, that there seems little point to that code if you're not using list once you're done populating it, as that's all that code does. If you're assigning list to something else when you're done (putting it on an object as a property, etc.), then there's still no need to set list to null, but the reason there's no need changes: If you're saving the list that list refers to somewhere else, then the list will have an outstanding reference, and it won't be eligible for garbage collection (whether you set list to null or not).

Upvotes: 1

Related Questions