#932 – When Objects Become Eligible for Garbage Collection

In general an object can be garbage collected when it is no longer referenced by any other object or reference-typed variable.  For example, the Dog object named “Kirby” is no longer referenced in the code snippet below when the myDog variable is set to null.

            Dog myDog = new Dog("Kirby", 15);
            myDog.Bark();

            Dog yourDog = new Dog("Ruby", 3);
            yourDog.Bark();

            // Kirby no longer referenced after this line executes
            myDog = null;

In practice, however, an object may become eligible for collection earlier than you think.  In the code sample above, the “Kirby” object will not be referenced at any time after the first call to the Bark method.  This means that the compiler may decide to garbage collect the “Kirby” object after the call to this method, i.e. before myDog is actually set to null.

 

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #932 – When Objects Become Eligible for Garbage Collection

  1. Pingback: Dew Drop – September 17, 2013 (#1,625) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: