Suppose I acquire a contextual reference of a bean programmatically, using BeanManager#getBeans(Type, Annotation...) and BeanManager#resolve(Set) and BeanManager#getReference(Bean, Type, CreationalContext). (This is standard stuff.)
Suppose further that the bean in question is in @Singleton scope (it could be any scope other than @Dependent; I've picked @Singleton just (a) to make this concrete and (b) to get client proxies out of the picture to keep it simple). (Note that strictly speaking I should be unaware of what scope applies to the bean I'm working with, but my question may be directly related to this.)
Suppose further that the bean in question has a @Dependent-scoped contextual reference "inside" it. (This helps to highlight the necessary pairing of bean destruction with CreationalContext#release(); see below.)
Suppose further that the reference I get back is the first such reference. That is, my acquiring this reference is what causes the underlying contextual instance singleton to be created. All fine and simple and good so far. Yay; I have my object.
I do whatever I'm going to do with this contextual reference. Now I have just created something and don't want to leak memory, so…what should I do?
- Should I simply try to destroy the existing contextual instance underlying the reference, perhaps using
AlterableContext#destroy(Contextual)? But don't I now have to know intimate details about the scope and whether it is suitable to destroy any existing instance? (And of course if I do this I'd better callCreationalContext#release()too.) - Should I simply release the
CreationalContextused for construction (without explicitly destroying the singleton instance)? But this will destroy the singleton's dependent references. That seems like something that would result in inconsistent state. - Should I do nothing? In the case of
@Singletonthis does no harm, since a singleton lasts for as long as the application, but, again, now I have to know intimate details about the scope. Is this by design?
Is the proper answer really that I need to know lots of things about the particular underlying scope (which, if user-supplied, it may be impossible to do), and need to tailor my destruction/releasing actions to the semantics of the scope?