ravi
ravi

Reputation: 1827

Regarding the scope and garbage collection in Spring bean container

I am new to Spring and I am currently using it in one of my projects. I learned that the Spring container holds all the beans and the scope of all the beans is "singleton" by default. I can change the scope either in the application-context.xml file or using the annotation @Scope. I furthermore learned that if a class has the scope "prototype", the Spring container will instantiate a new object of this class whenever needed.

What I don't understand: How is garbage collection handled. Will the created objects be garbage collected if they are no longer required or will they still be kept in the container. Obviously, I do not want many objects to be created and kept in order to keep memory usage low.

Upvotes: 22

Views: 9970

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

From Spring documentation (3.5.2 The prototype scope):

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.

Simply put - once you create and obtain a reference to prototype scoped bean, it is the only reference existing in the JVM. Once this references gets out of scope, the object will be garbage collected:

void bar() {
  Object foo = ctx.getBean("foo")
}

The moment you leave bar() method there aren't any other references to new instance of foo, which means it is eligible for garbage collection. The consequence of this model is:

Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.

Upvotes: 40

Dave Newton
Dave Newton

Reputation: 160170

The container doesn't keep a reference to instantiated beans, the code that's using them does.

If nothing else references the bean (roughly), it's eligible for GC.

Upvotes: 4

Related Questions