0

As Java programming has constructor that runs code when a new object is instantiated, I was curious if there was something to counter that. Creating new object occupies memory, so is there a mechanism in Java to erase or overwrite the unused memory?

If there a destructor in Java, then how does it differ from other memory management systems in programming languages such as C?

Abhishek Upadhyaya
  • 366
  • 1
  • 6
  • 15
  • 4
    Nope.. But there is something called as `Garbage Collector` which takes care of that automatically... – Codebender Jun 24 '15 at 07:11
  • 1
    There's "finalize", but it is not actually a destructor. Here is an article about clean-up in Java: http://www.javaworld.com/article/2076697/core-java/object-finalization-and-cleanup.html – Fildor Jun 24 '15 at 07:13
  • 1
    You can use java.lang.ref.Reference to somehow manipulate when an Object might be GCed. – Laurent B Jun 24 '15 at 07:15
  • 2
    no but there are other mechanism like finalize() mehtod and Garbage colector. And what do you mean by counter the constrcutor? – RajSharma Jun 24 '15 at 07:23

2 Answers2

3

you can override the finalize Method defined in java.lang.Object

there is no guarantee that your finalize methods are ever called during your program run ! Have a look at the JavaDoc ! In most cases it is therefore not a good idea to override 'finalize'.

if you need to clean up resources you could use a 'try/finally' statement or if you use some framework like 'Spring' some hook provided by the framework (e.g. @PreDestroy )

Btw.: in java you can't actively erase or overwrite memory areas, this is done by the garbage collector.

André R.
  • 1,627
  • 10
  • 14
1

In java for erasing memory which is in used with objects which have not any references(which called garbage) in code there is a mechanism called garbage callector. JVM call it when ever it is necessary but you can call it by System.gc().

As counter for constructor(which is some code which execute when an object instantiated) there is finalize method which execute when an object is garbage collecting.

You can override it(which is defined in Object class).

A.v
  • 734
  • 5
  • 26