CDI Instance Injections and Session/Application Scoped Beans

If you’ve spent much time with CDI you invariably had a use case where you would prefer not to trigger an injection when the bean is initialized. This can be handy for example if it is an expensive action and the injected bean is only going be be invoked a small percentage of the time.

There is however caveat that is relevant. The beans produced by the Instance will live until the containing bean is destroyed.

This doesn’t cause an issue with Dependent, Request, View, or Conversation scoped beans, but it would cause a unexpected memory leak with Application or even Session scoped beans. Since the Instance could be invoked multiple times spanning hours or days with a @SessionScoped bean and potentially weeks or months with an @ApplicationScoped bean (if your lucky to run your app uninterrupted that long) the memory leak could bring your app to a halt.

Improvement are being made to the CDI 1.1 spec to handled this better CDI-139

But in the meantime the following will work nicely

@Inject
BeanManager bm;

public void run() {

  CreationalContext<Foo> ctx = bm.createCreationalContext(null);
  Bean<?> beans = BeanManagerTools.beans(bm, Foo.class);
  Foo f = bm.getReference(beans, Foo.class, ctx);

  //Do Work

  ctx.release();
}

Calling the release at the end destroys all the beans created in the Context we initialized (ctx)

tags: java cdi
Cody Lerum - December 16, 2011
About outjected.com

Outjected is an infrequent blog about the frequent issues and annoyances that pop up while coding.

These are living posts and will be updated as errors or improvements are found.
About Me
Google+