2

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?

ford prefect
  • 7,096
  • 11
  • 56
  • 83
  • 1
    It depends on what LoggerFactory.getLogger() does. If it keeps a reference to the created logger, it won't be GCed. If it doesn't, then it will be GCed... some time. – JB Nizet Dec 17 '15 at 17:34

4 Answers4

7

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

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

the8472
  • 40,999
  • 5
  • 70
  • 122