When I started learning about OSGi in late 2008, it felt quite simple, mostly due to the specification’s clarity and design. But a year ago I thought that designing code for OSGi might give me the greatest challenge I’ve ever had with software design. Or so I thought until I realized those design “challenges” were solved decades ago.
Here are few examples of those “challenges”. First, I noticed that most examples I’ve seen for a service bundle and its client are separated by an API bundle of some kind. Makes sense, I thought, as using an interface between the provider of a service and its user makes it possible to replace the service implementation. But, actually, those API bundles were not made for that at all. The class instances passed from the service to its client, through whatever interface, must not be created by the classloader of the service’s package, otherwise if the service is unloaded its classloader will “leak” in memory until all of its created object instances are garbage-collected. Since the instance’s package defines what bundle’s classloader to use to create it, then defining those “interface beans” in an API bundle prevents that “classloader leak” problem.
Second, you shouldn’t be using BundleContext.getServiceReferences(String, String)
, unless you’re planning on calling BundleContext.ungetService(ServiceReference)
on all of them right away. Actually, if you want to “bind” a bundle to some service by getting its ServiceReference
, you should do so outside of BundleActivator.start()
, because it “must complete and return to its caller in a timely manner” and you can’t block to wait for another service to start. Actually, you should use a ServiceListener
and listen for service registration asynchronously, so if you really want to “block” in start()
, instead start a thread that gets awakened by ServiceListener
events.
That second point introduced me to a new perspective on how lifecycle initialization in IoC and modular systems actually imply.
Published on June 3, 2010 at 13:21 EDT
Older post: Markdown Test
Newer post: Our National Moving Day