Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 292
ankush981 Avatar asked Mar 25 '26 20:03

ankush981


1 Answers

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.

like image 120
K Erlandsson Avatar answered Mar 28 '26 11:03

K Erlandsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!