Object deletion in Java

Suppose I have many geometries attached to the root node and that they all share the same material. If I detach one of these geometries, will it be “destroyed”, i.e. it’s memory will be freed by the garbage collector when it will search for unreferenced objects?

Another way of asking this question is : for an object to be deleted by the garbage collector in single threading, does it need to be unreferenced by an object on the main thread and not reference any other object on the main thread?

Detaching eliminates the reference that root node has to your geometry.

If it is the only one in your application and you have no other pointers on any other object then yes, the garbage collector will free your geometry’s memory.

There is no such thing as circular references in Java, it has a full garbage collector. If an Object can’t be reached anymore it will be removed from memory, even if it’s referenced by other Objects that can’t be reached.

Hmmm so if an object is not referenced but references other objects on the main thread, it will be deleted?

Yes, even if those objects are still actives.

Sounds to me like you’re coming from a C/C++ background where you’ve got to manage everything yourself or disaster beyond all imagination occurs. Compared to that, Java’s GC is almost a get-out-of-jail-free card. Any object that is no longer reachable will be reclaimed, and it doesn’t matter if the objects are part of some horribly convoluted object graph or not. If some object has no more references to it (or only weak/phantom references, which are library classes that you will not be using without knowing) the GC will reclaim it - end of story. Sit back and relax with a nice glass of iced tea. :wink:

Of course, if you’re using native resources (like OpenGL objects in jME’s case, files, network sockets, threads, etc.) you need to be careful to release them because they aren’t Java objects so the GC can’t do anything about them.

1 Like

Ok thank you all for clearing that out for me.

I actually come from a mix of C# / C++ and Java background. However, we studied Java specifically in college but, unlike my fellow class colleagues, I studied intensively C++ due to a personal interest for that language :slight_smile:

I had an interest in C++ at one point. Then at my day job I was one of the designers for a C++ rendering backend. Ouch. No thanks. :stuck_out_tongue:

(C# functions similarly to Java in terms of the GC, just FYI - if an object is no longer reachable it’s reclaimed, even if it’s part of an object graph containing reachable objects.)

1 Like