Java Reference
In-Depth Information
(continued)
These need to be closed to free up resources, and that's exactly the same reasoning
used in OSGi. As we mentioned in section 1.2.3, OSGi began life in constrained sys-
tems. Every byte of memory was precious, so reducing the footprint was important.
You'll see in more detail in section 6.3.4 how services can be lazily created, but for
now it's enough to know that you can create a service object dynamically when it's
requested. The framework caches this result, speeding up future lookups and reducing
memory usage. If the service is no longer being used, then this caching is a waste of
memory. By ungetting the service you're letting the framework know that it can inval-
idate its cache (assuming nobody else needs the service), and that any resources
associated with the service can be cleaned up.
Listing 6.2
Consuming a single OSGi service using the OSGi API
public void callService(BundleContext ctx) {
String name = SpecialOffer.class.getName();
ServiceReference ref = ctx.getServiceReference(name);
if (ref != null) {
SpecialOffer s = (SpecialOffer) ctx.getService(ref);
if (s != null) {
try {
Food f = s.getOfferFood();
} finally {
ctx.ungetService(ref);
Find service that
advertises right interface
Check that service exists
Get
instance
Service instance could
have been unregistered!
You can finally
call service
You must
unget service
}
}
}
}
You first use the bundle context to find services that are registered under an interface
name you supply. A null return indicates that you couldn't find any services with the
right interface name. Then you can use the bundle context to get the service instance
for the service you looked up. But between doing the initial lookup and getting the
instance, the service might have been unregistered, in which case it's no longer avail-
able. (Have we mentioned OSG i is dynamic?) After you have a service instance, you're
safe to use it. But you need to remember to unget the service when you're done with it.
The best way to get services?
Even though listings 6.2 and 6.3 aren't short, they don't show all the possible com-
plexity of getting services using the low-level OSGi APIs in a real application. If you
showed this code to an OSGi expert, you'd get a lot of furrowed brows and concerned
noises. This sample may not perform well, because it doesn't keep hold of the ser-
vice for long.
Search WWH ::




Custom Search