Home > other >  Release unused spring beans
Release unused spring beans

Time:11-03

My application has lot of Spring beans (singleton and effectively stateless).
Do the bean instances add to the application's total memory?

If the beans are unused for a long time, is it possible to release them to be garbage collected?

(I know that the prototype scope is available, but I want only a single instance of the bean to exist at any given time.)

CodePudding user response:

The whole point of the singleton bean is to be a single instance per application context. When spring application starts, these beans are created and put into the context.

They'll reside in the context as long as the application context is available (usually it means as long as the application process is up and running).

Now If beans are stateless, I doubt they'll significantly impact the memory footprint. JVM can allocate millions of objects, and usually, the memory is consumed by the internal state of the allocated object...

If you do have a state - you can define a cache with an expiration so that it will be cleaned and eventually garbage collected... Spring has caching support or alternatively you can use the in-memory cache implementations directly (like caffeine or guava cache) - no need to roll your own cache implementation from scratch.

CodePudding user response:

Do the bean instances add to the application's total memory?

Sure, they will contribute to the application memory footprint. Your Singleton-Beans are there would be there from the application start up, fully initialized and ready to serve requests without any delay, that's the whole point of keeping them alive in the Spring's Context.

If the beans are unused for a long time, is it possible to release them to be garbage collected?

It feels like you want to address the problem backwards, by trying to mitigate the symptoms without touching the root.

If you have too many Beans that are unused for a significant amount of time (and presumably the application is constantly busy) the problem might be rooted on the Architectural level. The solution (not the easy one) might be to split it into multiple services shipped with more granular subsets of functionalities (which are now you have in a single application) deployed and managed separately.

  • Related