user705414
user705414

Reputation: 21220

When will an object reference get garbage collected?

Someone told me only when a reference be set as null, the garbage collector will collect it. However I think the garbage collector will collect all out of scope references, which have never been set as null.

Anyone can told me when a reference will be claimed by the garbage collector?

Upvotes: 3

Views: 1722

Answers (3)

Piotr Gwiazda
Piotr Gwiazda

Reputation: 12222

GC will removes an object from memory "when it wants". You can try to run System.gc() but it's just a hint for GC that it should run. Whne GC runs, it finds non-referenced objects (or objects with weak references etc. only). GC runs frequency depdens on memory space. It runs most often in eden space. By default GC runs in eden space when it gets full, but you can tune up your JVM.

Why are you bothering GC in the first place? What's your problem?

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

What that someone probably meant was that you can let GC collect an object before it goes out of scope by setting the variable that holds a reference to that object to null. This technique has been of value in the past for some very rare cases (for example, before a long-running loop that does not reference an object). The compiler technology these days renders this idea virtually useless, because compilers are smart enough to detect these conditions, and act accordingly.

Upvotes: 2

SLaks
SLaks

Reputation: 888203

The GC collects objects, not references.

The GC will collect an object some time after it has no more live references. (the GC is non-deterministic)

Upvotes: 9

Related Questions