ford prefect
ford prefect

Reputation: 7378

Garbage Created By Object that is Never Referenced

Is any garbage created by an object that is never referenced?

The example I am thinking of is using a static factory method to create an object then having that object perform a function but never creating a reference to it.

For Example:

LoggerFactory.getLogger(Foo.class).info("logging some stuff");

Does this just create an unreferenced object in eden space that will be garbage collected as soon as the next collection happens?

Upvotes: 2

Views: 64

Answers (4)

the8472
the8472

Reputation: 43042

Does this just create an unreferenced object in eden space that will be garbage collected as soon as the next collection happens?

Maybe, maybe not. The Logger instance is referenced as this inside info()

E.g. if info() then creates an anonymous inner class or a this-capturing lambda and puts it on a task queue then the Logger instance may live longer than the line of code in your question.

In most scenarios it is likely still be very short-lived. But you cannot know that for certain from the single line of code.

On the other end of the spectrum the object may never be allocated on the heap in the first place, i.e. not even in eden space, due to Escape Analysis

Upvotes: 1

John Bollinger
John Bollinger

Reputation: 180058

Java GC works by periodically analyzing which objects are reachable via a chain of references. That does not depend on whether those objects ever were reachable in the first place.

Your question suggests that you think GC may watch for references to be reclaimed to determine which objects to collect. Although GC is not forbidden from doing so, it cannot rely exclusively on such a strategy, and I am unaware of any existing Java GC implementation employing it.

Upvotes: 1

Kayaman
Kayaman

Reputation: 73528

Provided that getLogger() doesn't store the created Logger somewhere (which is quite possible), then yes. The garbage collector is very good at disposing short lived objects, so it should get GCd quite quickly.

Of course nobody would write that specific logging line, since it makes no sense.

Upvotes: 1

Mureinik
Mureinik

Reputation: 310993

getLogger returns an instance - whether it creates a new one or returns a previously cached one is up to the LoggerFactory's implementation. If this object is no longer referenced from inside the factory in some way, it would be eligible for garbage collection.

Upvotes: 7

Related Questions