Search code examples
javaosgiipojo

iPojo instance creation and management


I am currently having lots of trouble with iPojo leaks due to constructed instances that we forget to dispose. I see this as an inevitable drawback of using imperative instantiation using the ipojo Factory technique: basically you say when you need your service by calling factory.createComponentInstance(config), so you have the responsibility to say when you are done with it. This forces me to keep two references, one for the service that I want to consume, but also a second one of the iPojo ComponentInstance so that when the consumer is done, it can call componentInstance.dispose(). If not, there's a leak

Is there a more declarative way to do this where the consumer doesn't need to handle the lifecycle of the iPojo service and its instance?

To simplify my usecase, imagine that there's a UI with a button in it and every time the button is pressed, i need a new, unique instance of an iPojo service. Ideally, the instance would be GC'd when it goes out of scope, without the consumer having to do anything

Maybe my mistake is using services as instances, but I have three reasons to use a service instead of a normal class and calling new.

  1. The service impl should be substitutable
  2. The consumer should depend on an interface, not an implementation/provider, not only because of #1 but also because of tons more transitive dependencies pulled when depending on a concrete impl
  3. The service impl has some dependencies itself that I'm hoping will be injected by iPojo (dependency injection).

As a second request, does anyone know of any opensource, real (i.e not dummy, demo) projects using iPojo that I can use as example of good usage of iPojo?


Solution

  • Instead of creating a component instance, you probably should use a custom 'creation strategy'. So you will have only one component instance, but with several 'implementation' instances (service objects) managed. You decide when these objects are created and disposed. More information on http://felix.apache.org/documentation/subprojects/apache-felix-ipojo/apache-felix-ipojo-userguide/describing-components/providing-osgi-services.html#service-serving-object-creation.

    About a project using iPOJO, you can have a look to Wisdom Framework, which relies on iPOJO: http://wisdom-framework.org (code available there: github.com/wisdom-framework/wisdom/)