Search code examples
cdiquarkus

Can Quarkus/CDI ApplicationScoped beans be removed from context or garbage collected at runtime for any reason?


My understanding is that these beans are simple java objects, but once they have survived being removed at build-time and have been (lazily) initialized, they are held in the context indefinitely and should not be GC-able even if they are idle for long times.

But I was unable to confirm it after running through the 2.0 CDI specs and the bean lifecycle/CDI related Quarkus docs.

Are there any specific cases where this could happen?


Solution

  • So in theory, you can do AlterableContext#destroy(Contextual<?>) - this would remove the contextual instance (i.e. the instance of your @ApplicationScoped bean) from the context, and then it can be garbage-collected if there are no other references.

    For example, in quarkus you can do Arc.container().instance(MyApplicationScopedFoo.class).destroy(). This would call the @PreDestroy callback if present, @PreDestroy interceptors if bound, and remove the MyApplicationScopedFoo instance from the application context.