Michael
Michael

Reputation: 4461

Finalize and garbage collection

Could you help me understand garbage collection.

When I force finalization, I am supposed to occur in finzlize method. I placed a breakpoint there.

Well, when I start debugging, my program finishes without stopping at that breakpoint. Could you help me understand what I'm doing wrongly?

public class Book {
    protected void finalize(){
        int a = 0; // Breakpoint;
    }
}

public class Test {
    public static void main(String[] args){
        Book a = new Book();
        System.gc();
    }
}

Upvotes: 1

Views: 113

Answers (2)

rachana
rachana

Reputation: 3414

Garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.

An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object.

An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

For more details Java Memory Management and How Garbage Collection works in Java

Upvotes: 1

Marwin
Marwin

Reputation: 2763

In this particular case, the new Book instance will not get garbage-collected because it is still referenced by the local variable a.

Also, as other answers suggest, it is not guaranteed that all objects are fully GCed (and their finalize called) before the System.gc returns. In particular, the finalize method may be called later in a different thread. If your main application terminates before that, the method may not get called at all.

Upvotes: 3

Related Questions