3

We can delete object in C++ as

delete <object>

How can I delete object in java without inbuilt garbage collector. If I perform

object = null

as per my knowledge it won't deallocate the memory. How can I free the space.

sdk
  • 178
  • 2
  • 19
  • You can't free up the memory. It is not under your control. You can make it available for garbage collection by not having any references to it. – khelwood Dec 04 '15 at 11:08
  • 1
    u shouldn't compare c++ and java in this manner, java has its own way of freeing memory by using GC. some say its good and some hate it, its just a matter of prefrences – nafas Dec 04 '15 at 11:15

3 Answers3

3

An object in java is eligible for garbage collection when you :

  1. Remove all the references to it.
  2. Leave the block where it was declared

When it becomes eligible, care will be taken by the JVM to free up the used memory by that object at appropriate time.

Manually calling System.gc() is not a good idea at all. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken. So, in short, there is no direct control of the programmer on the memory allocation/ deallocation.

Sagar D
  • 2,588
  • 1
  • 18
  • 31
2

You don't need to.

The Garbage Collector will do that any time it pleases.

As long as there's no live reference to an object anymore it will be released ... then :-)

Jan
  • 13,738
  • 3
  • 30
  • 55
0

In Java there isn't "loss of memory" as there is in c++. You don't need to free this memory, the Garbage Collector will do it for you.

You can find more information about the Garbage Collector in this link: http://www.cubrid.org/blog/dev-platform/how-to-tune-java-garbage-collection/

And perhaps this link Is there a destructor for Java? could be usefull to you.

Community
  • 1
  • 1
Jose Luis
  • 994
  • 1
  • 8
  • 22