Java Reference
In-Depth Information
Revisiting the magic method
Recall that in chapter 3, when you implemented the refresh command for the shell,
you had to use the magic getPackageAdminService() method to acquire the Pack-
age Admin Service. Now you have enough knowledge to see what was happening be-
hind the scenes:
private PackageAdmin getPackageAdminService() {
return (PackageAdmin) m_context.getService(
m_context.getServiceReference(
PackageAdmin.class.getName()));
}
This method is simple—probably too simple, as you'll find out later in section 4.3.1.
You use the BundleContext to find a service implementing the Package Admin Ser-
vice interface. This returns a service reference, which you use to get the service im-
plementation. No more magic!
Each time you call getService() , the registry increments a usage count so it can keep
track of who is using a particular service. To be a good OSG i citizen, you should tell
the registry when you've finished with a service:
bundleContext.ungetService(reference);
listing = null;
Services aren't proxies
In general in OSGi, when you're making method calls on a service, you're holding a
reference to the Java object supplied by the providing bundle. For this reason, you
should also remember to null variables referring to the service instance when you're
done using it, so it can be safely garbage collected. The actual service implementa-
tion should generally never be stored in a long-lived variable such as a field; instead,
you should try to access it temporarily via the service reference and expect that the
service may go away at any time.
You've now seen how to publish simple Java POJO s as OSG i services, how they can be
discovered, and how the registry tracks their use. But if you remember one thing from
this section, it should be that services can disappear at any time. If you want to write a
robust OSG i-based application, you shouldn't rely on services always being around or
even appearing in a particular order when starting your application. Of course, we
don't want to scare you with all this talk of dynamism. It's important to realize that
dynamism isn't created or generated by OSG i—it just enables it. A service is never arbi-
trarily removed; either a bundle has decided to remove it or an agent has stopped a
bundle. You have control over how much dynamism you need to deal with, but it's
always good to code defensively in case things change in the future or your bundles
are used in different scenarios.
Search WWH ::




Custom Search