Search code examples
javac#objective-cgarbage

How should I properly FULLY delete an object? (C#, Objective-C, Java)


I haven't found or discovered a clear answer of this yet. I am not asking about a specific language but am talking about all OOP languages in general.

If I have an object for example:

Object obj = new Instance();

Lets say I no longer need this object. Of course I could simply do as follows:

obj = null;

However, correct me if I am wrong, this simply means the obj variable is no longer assigned as "new Instance();" but does not mean that "new Instance();" no longer exists. So my question is: How can I make sure the instance object is COMPLETELY removed from the system and no longer exists. How can I be completely sure the instance no longer exists?

I program in Objective-C, Java, and C#, so an answer relative to those languages would be great as I am aware garbage cleaners work differently in different languages and in some languages don't even exist.

I know you cannot completely clear an instance in some languages however what would be the best way to free up memory with the object?

Thanks so much!


Solution

  • As others have said, the removal of the object from memory itself is out of your control with Java. Your only requirement is to unassign all references to this object so that it becomes eligible for garbage collection, but when GC actually runs is neither determinable nor reliably consistent.

    There is a System.gc() call which you can read into, but it should probably just be avoided entirely.