15

I am confuse in between system.gc() and finalize() method of java. We can't force to collect garbage object to JVM. We are allow to write both methods in our java code then if both are used for garbage collection, then what is point in providing two methods for garbage collection by java?

Please tell me the exact working of both methods and internally how it works?

sayali
  • 255
  • 2
  • 3
  • 8

8 Answers8

13

System.gc() kindly asks the sytem to perform a garbage collection. Javadoc says:

Runs the garbage collector.

You can not control how "hard" the garbage collector will work. How the garbage collector work internally is VM-specific and a research topic on its own. But there are usually "full" garbage collection and some smaller "incremental" collection going on. So consider System.gc as a request, but there's not guaranteed that garbage collection of your object will happen.

Object.finalize() can be overriden to specify what to do when a given object is garbage collected (actually what to do just before it is garbage collected). Javadoc says:

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Classical use of finalizer are to de-allocate system resources when an object is garbage collected, e.g. release file handles, temporary files, etc.

Do not use finalizer to perform actions when the JVM exits. For this purpose use a shutdown hook that you register with Runtime.getRuntime().addShutdownHook(Thread).

AADProgramming
  • 6,077
  • 11
  • 38
  • 58
ewernli
  • 38,045
  • 5
  • 92
  • 123
  • The JVM is going to be unaware of any "kindness" ... or "politeness" ... in your call to `System.gc()`. It will work the same if you make the call rudely :-) – Stephen C Apr 17 '12 at 06:46
  • @StephenC Yeah :) What I meant is that you depend on the kindness fo the garbage collector reclaim space as demanded: "the Java Virtual Machine has made *a best effort* to reclaim space from all discarded objects". You can not control how hard it tried :) – ewernli Apr 17 '12 at 06:53
2

System.gc() forces the garbage collector to run, while the Finalize() method of your object defines what garbage collector should do when collecting this specific object.

Roughly speaking, it is like this:

class MyClass {
    public UnmanagedResource resource;

    void Finalize() {
        FreeUnmanagedResource(resource);
    }
}

MyClass[] data = new MyClass[1000];
for(int i=0; i<1000; i++) {
    data[i] = new MyClass();
}
//do some work
data = null;
System.gc(); //Note that it doesn't guarantee you that all MyClass instances will be actually collected at this point.
penartur
  • 9,792
  • 5
  • 39
  • 50
  • 1
    `System.gc()` definitely does not force GC to run. It only notifies GC that app wants GC to run, but there is no guarantee that anything will happen. – ctomek Mar 13 '17 at 13:29
1

system.gc() method notifies the JVM that the garbage collector can run now to clear the memory by deleting unused objects. As per the java doc:

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

finalize() method will not trigger garbage collector instead it will be called while the garbage collector about the destroy the object. It provides the instructions to clear the object properly.

Jason Braucht
  • 2,358
  • 19
  • 31
vinothM
  • 195
  • 1
  • 6
1

The System.gc() method garbage collects the objects that are created by a new keyword, whereas the finalize() method is used when we want to garbage collect the objects that are not created using a new keyword. So, I guess this ans. your Q

Priyantha
  • 4,839
  • 6
  • 26
  • 46
learner
  • 21
  • 1
  • 4
1

The answers here are great, just wanted to elaborate small point about the finalize() method: you should never use it. It's execution is not guaranteed at all and eventually the usage of finalize() adds performance penalty.

As written in Effective Java by Joshua Bloch:

Finalizers are unpredictable, often dangerous, and generally unnecessary. never do anything time-critical in a finalizer. never depend on a finalizer to update critical persistent state.

And:

Oh, and one more thing: there is a severe performance penalty for using finalizers. On my machine, the time to create and destroy a simple object is about 5.6 ns. Adding a finalizer increases the time to 2,400 ns. In other words, it is about 430 times slower to create and destroy objects with finalizers.

Prefer using the following resource terminating try-finally pattern, which are guaranteed to run:

Bar bar = new Bar(...);
try {
    // Your code here
} finally {
    bar.releaseResource(); // You implementation. For example close connection
}
Johnny
  • 14,397
  • 15
  • 77
  • 118
0

Garbage collection is used to reclaim the allocated memory of object and Finalize() is called by garbage collector before reclaiming the memory Finalize() method mostly used to do some operation before deleting the object

swan
  • 21
  • 2
  • 1
    Not after. An object is still usable when finalize() gets called and it is one fine place to make hard-to-find memory leaks by re-referencing the object with some other object. – heikkim Apr 17 '12 at 06:31
0

There are many classes that contain the finalize() method, I'll assume you mean the one in the Object class. System.gc() is what you call when you want Java's garbage compiler to run. It will run by itself every few minutes, but you can ask it to go whenever you want. When the garbage collector runs, it calls the finalize() method on each object that has no more reference. Basically, System.gc() cleans up memory and uses finalize() to get rid of the individual objects.

Priyantha
  • 4,839
  • 6
  • 26
  • 46
Jainendra
  • 24,713
  • 30
  • 122
  • 169
0

Garbage collector is invoked by calling the System.gc() method on any class. But it does not guarantees that all the nullified objects will be garbage collected before jvm shuts down. So basically gc() method is garbage collecting only those objects which are created using new keyword. Objects are created by any other logic than this will be garbage collected by explicitly calling finalize() method before gc calls the garbage collector.

Charuක
  • 12,953
  • 5
  • 50
  • 88