Java Reference
In-Depth Information
What happens if your bundle stops before you've removed all your published services?
The framework keeps track of what you've registered, and any services that haven't yet
been removed when a bundle stops are automatically removed by the framework. You
don't have to explicitly unregister a service when your bundle is stopped, although it's
prudent to unregister before cleaning up required resources. Otherwise, someone
could attempt to use the service while you're trying to clean it up.
You've successfully published the service in only a few lines of code and without
any use of OSG i types in the service implementation. Now let's see if it's just as easy to
discover and use the service.
4.2.2
Finding and binding services
As with publishing, you need to take details from the service contract to discover the
right services in the registry. The simplest query takes a single interface name, which is
the main interface you expect to use as a consumer of the service:
ServiceReference reference =
bundleContext.getServiceReference(StockListing.class.getName());
This time the registry returns a service ref-
erence, which is an indirect reference to
the discovered service (see figure 4.10).
This service reference can safely be
shared with other bundles, because it isn't
tied to the lifecycle of the discovering
bundle. But why does the registry return
an indirect reference and not the actual
service implementation?
To make services fully dynamic, the
registry must decouple the use of a ser-
vice from its implementation. By using an
indirect reference, it can track and con-
trol access to the service, support lazi-
ness, and tell consumers when the service
is removed.
Direct method calls
ServiceReference
ctx.getService
( )
( )
ctx.ungetService
OSGi
service
registry
Figure 4.10 Using an OSGi service
CHOOSING THE BEST SERVICE
If multiple services match the given query, the framework chooses what it considers to
be the “best” services. It determines the best service using the ranking property men-
tioned in table 4.2, where a larger numeric value denotes a higher-ranked service. If mul-
tiple services have the same ranking, the framework chooses the service with the lowest
service identifier, also covered in table 4.2. Because the service identifier is an increasing
number assigned by the framework, lower identifiers are associated with older services.
So if multiple services have equal ranks, the framework effectively chooses the oldest ser-
vice, which guarantees some stability and provides an affinity to existing services (see fig-
ure 4.11). Note that this only applies when you use getServiceReference —if you ask
Search WWH ::




Custom Search