Prioritizing OSGi service selection within a container when more than one implementation exist

mP. picture mP. · Dec 5, 2009 · Viewed 7.1k times · Source

I am playing with OSGi and have a few bundles. Bundle A and B both contain a registered service which implements a single interface. The third bundle C includes code to lookup a service implementing the previously mentioned interface. The A and B bundles have different version numbers, however it appears that C picks up the service from the first started bundle. I have changed the start level to do the right thing, but version is only used to accept rather than order which service is returned.

   A version 1.0 start level 1
   B version 1.1 start level 2
   C requires both bundles, start level 3

In the above example C always gets the service from A even though B has a higher bundle version. However, if I switch the start level, so B starts before A, C sees the B service.

I have searched the OSGi website and there is no clear explaination of whether versioning of a bundle is used to prioritise a service over another. My understanding seems to indicate that start level is supposed to be used to order bundle startup so that dependencies can be satisified correctly. However it appears to be overloaded so that it also prioritises service priority. Given all the above, I guess it makes sense not to use the bundle version in selection because the version number is just a number relative to nothing.

What is the best way to prioritise one service over another, besides start level?

Answer

Pavol Juhos picture Pavol Juhos · Dec 5, 2009

The best way of prioritizing OSGi services to use SERVICE_RANKING service property. This property may be supplied in the properties object passed to the BundleContext.registerService() method.

According to the documentation of the BundleContext.getServiceReference() method:

If multiple such services exist, the service with the highest ranking (as specified in its Constants.SERVICE_RANKING property) is returned.

If there is a tie in ranking, the service with the lowest service ID (as specified in its Constants.SERVICE_ID property); that is, the service that was registered first is returned.