Sumithra
Sumithra

Reputation: 6707

Garbage Collection in java

While isolating reference (islands of isolating) a class objects say like the below code

public class Island {
    Island i;
    public static void main(String [] args) {
        Island i2 = new Island();
        Island i3 = new Island();
        Island i4 = new Island();
        i2.i = i3; // i2 refers to i3
        i3.i = i4; // i3 refers to i4
        i4.i = i2; // i4 refers to i2
        i2 = null;
        i3 = null;
        i4 = null;
        // do complicated, memory intensive stuff
    }
}

will these objects be garbage collected? How is that possible then what makes the program run if they are garbage collected?

Upvotes: 2

Views: 294

Answers (4)

mdrg
mdrg

Reputation: 3402

As for the 'what makes the program run if they are garbage collected', guess that you are missing is that only some Island object instances were GCed, and you start running a program on a static method (main), which does not need any object of its class (Island) to be called.

The thread that the JVM created to execute your 'main' method will keep your application alive as long as it remains executing something (or you create another thread).

Upvotes: 1

symcbean
symcbean

Reputation: 48357

Yes (unless you've got a very old jvm) but only in a major collection. But using recursive classes like this is a bit iffy.

Upvotes: -1

foret
foret

Reputation: 728

In Sun JVM they will be collected.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240860

will these objects be garbage collected?

It is dependent on JVM, we can't surely say that object has been GCed.

Further we can only say that they are ready to GCed.

And It will GCed when there is no live ref to Object exist . so you no need to worry about your program JVM will make sure:)

Upvotes: 11

Related Questions