how to destroy an object in java?

creating and destroying objects in java
java destroy variable
java finalize
java deallocate object
garbage collection in java
java destroy array
java dispose
java remove all references to object

I encountered this question in an interview with following options:

How to destroy an object in java?

a. System.gc();  
b. Runtime.getRuntime.gc();  
c. object.delete();  
d. object.finalize();  
e. Java performs gc by itself, no need to do it manually.
  1. The answer should be e?

  2. what if e was not there? then ? clearly c is not the answer. a and b will do gc for the whole application(question requires for one object). I think it is d because finalize() is called just prior to gc(but is it necessary that after finalize gc is invoked ?) or I am wrong ? e must be there to answer this question ?

Answer E is correct answer. If E is not there, you will soon run out of memory (or) No correct answer.

Object should be unreachable to be eligible for GC. JVM will do multiple scans and moving objects from one generation to another generation to determine the eligibility of GC and frees the memory when the objects are not reachable.

What method in Java is used to destroy your objects, Which function is used to destroy a variable or object? Thus, the interpreter is able to determine when an allocated object is no longer referred to by any other object or variable. When the interpreter finds such an object, it knows it can destroy the object safely and does so. The garbage collector can also detect and destroy cycles of objects that refer to each other,

To clarify why the other answers can not work:

  1. System.gc() (along with Runtime.getRuntime().gc(), which does the exact same thing) hints that you want stuff destroyed. Vaguely. The JVM is free to ignore requests to run a GC cycle, if it doesn't see the need for one. Plus, unless you've nulled out all reachable references to the object, GC won't touch it anyway. So A and B are both disqualified.

  2. Runtime.getRuntime.gc() is bad grammar. getRuntime is a function, not a variable; you need parentheses after it to call it. So B is double-disqualified.

  3. Object has no delete method. So C is disqualified.

  4. While Object does have a finalize method, it doesn't destroy anything. Only the garbage collector can actually delete an object. (And in many cases, they technically don't even bother to do that; they just don't copy it when they do the others, so it gets left behind.) All finalize does is give an object a chance to clean up before the JVM discards it. What's more, you should never ever be calling finalize directly. (As finalize is protected, the JVM won't let you call it on an arbitrary object anyway.) So D is disqualified.

  5. Besides all that, object.doAnythingAtAllEvenCommitSuicide() requires that running code have a reference to object. That alone makes it "alive" and thus ineligible for garbage collection. So C and D are double-disqualified.

Garbage Collection in Java, logic manually, similarly to how you do this in Java. On the other hand an object is also eligible for garbage collection if it runs out of scope that is the program in which we created the object is terminated or ended. Coming to your question the method finalize is same as the destructor in C++. The finalize method is actually called just before the moment of clearing the object memory by the JVM.

Short Answer - E

Answer isE given that the rest are plainly wrong, but ..

Long Answer - It isn't that simple; it depends ...

Simple fact is, the garbage collector may never decide to garbage collection every single object that is a viable candidate for collection, not unless memory pressure is extremely high. And then there is the fact that Java is just as susceptible to memory leaks as any other language, they are just harder to cause, and thus harder to find when you do cause them!

The following article has many good details on how memory management works and doesn't work and what gets take up by what. How generational Garbage Collectors work and Thanks for the Memory ( Understanding How the JVM uses Native Memory on Windows and Linux )

If you read the links, I think you will get the idea that memory management in Java isn't as simple as a multiple choice question.

How to Delete an Object In PHP, Destroying and Finalizing Objects. Now that we've seen how new objects are created and initialized in Java, we need to study the other end of the object life  The java.lang.Process.destroy() method kills the subprocess. The subprocess represented by this Process object is forcibly terminated. The subprocess represented by this Process object is forcibly terminated.

Set to null. Then there are no references anymore and the object will become elligable for Garbage Collection. GC will automatically remove the Object from the heap.

How to destroy an singleton Object in Kotlin and force to call init , finalize() is called before an object is finally destroyed. There is no way to forcefully release all memory being held by the object (i.e. completely  You cannot destroy an object, only the JVM can do that. Once an object is inaccessible by any live threads, it then becomes eligible for garbage collection. SCJP 1.4, SCWCD 1.3, SCBCD 1.3

Here is the code:

public static void main(String argso[]) {
int big_array[] = new int[100000];

// Do some computations with big_array and get a result. 
int result = compute(big_array);

// We no longer need big_array. It will get garbage collected when there
// are no more references to it. Since big_array is a local variable,
// it refers to the array until this method returns. But this method
// doesn't return. So we've got to explicitly get rid of the reference
// ourselves, so the garbage collector knows it can reclaim the array. 
big_array = null;

// Loop forever, handling the user's input
for(;;) handle_input(result);
}

Destroying and Finalizing Objects (Java in a Nutshell), Java saves you from this by allowing you to create as many objects as you want (​limited of course to whatever your system can handle) but never having to destroy  Questions: Recently, I came across one of my application which consumes too much memory and increasing by 10 MB/sec. So, I like to know the best way to destroy JavaScript object and variables so memory consumption stay down and my FF can’t get destroyed.

How to create and destroy objects, This cannot be done manually. Garbage Collector only can destroy an object. If all the links that refer to an object are assigned to a null value, the object itself  The object obj will be destroyed now or if a time is specified t seconds from now. If obj is a Component it will remove the component from the GameObject and destroy it. If obj is a GameObject it will destroy the GameObject, all its components and all transform children of the GameObject.

destroy objects (Java in General forum at Coderanch), Even though the programmer is not responsible to destroy useless objects but it is highly recommended to make an object unreachable(thus eligible for GC) if it  Java is not like VB (for example) where setting an object to null frees it up. Whether or not the GC decides it can destroy the object is more complex than checking its value, indeed the GC can destroy object which have non-null values.

Cleaning Up Unused Objects, If the parameters to a constructor do not, in and of themselves, describe the object being returned, a static factory with a well-chosen name is  Three items that involve creating and destroying Java objects Editor's Note : This article is based on Effective Java, Second Edition , by Joshua Bloch, which presents proven rules ("items") for improving your programs and designs (a format, by the way, borrowed from Scott Meyers's Effective C++ .

Comments
  • If e wasn't there, write it yourself. None of the other options is the answer.
  • Java doesn't let you destroy objects. Any unreachable object may (or may not) be GCed at any particular point in time.
  • That is correct. There's no correct answer but E. Else Java would become C++.
  • This still isn't 100% correct, objects can live for the entire time of the application even though they are "not reachable", that doesn't have as much to do with their removal as does memory pressure. The JVM doesn't try to maintain max free space, that would be a waste of resources.
  • Thank you for this answer. its help for me.
  • There should be a programming language where gems like this should be legal statements -> object.doAnythingAtAllEvenCommitSuicide()