ankush981
ankush981

Reputation: 5417

Explain this System.gc() behavior

In the book Thinking in Java, the author provides a technique to force garbage collection of an object. I wrote a similar program to test this out (I'm on Open JDK 7):

//forcing the garbage collector to call the finalize method
class PrintMessage
{
    private String message;

    public PrintMessage (String m)
    {
        this.message = m;
    }

    public String getMessage()
    {
        return this.message;
    }

    protected void finalize()
    {
        if(this.message == ":P")
        {
            System.out.println("Error. Message is: " + this.message);
        }
    }
}

public class ForcingFinalize
{
    public static void main(String[] args)
    {
        System.out.println((new PrintMessage(":P")).getMessage());
        System.gc();
    }
}

The trick, as it appear to me, is to create a new object reference and not assign it: new PrintMessage();.

Here's what's mystifying me. When I compile and run this program, I get the following expected output:

:P
Error. Message is: :P

However, if I modify the first line of my main() function like this:

(new PrintMessage(":P")).getMessage();

I do not see any output. Why is it that System.gc() is calling the garbage collector only when I send the output to standard output? Does that mean JVM creates the object only when it sees some "real" use for it?

Upvotes: 3

Views: 219

Answers (1)

K Erlandsson
K Erlandsson

Reputation: 13696

The object will be created, the bytecode compiler will not optimize that away. What happens in the second case is that your program exits before the output is actually flushed to your terminal (or maybe even before the finalizer is run, you never know when the GC and finalization actually happens). If you add a Thread.sleep() after the System.gc() call you will see the output.

Upvotes: 4

Related Questions