Java Reference
In-Depth Information
You picked up the basics of discovering services in section 4.2.2. In the following sec-
tion, you'll take that knowledge and use it to look up and call the Log Service; we'll
point out and help you solve potential problems as we go along.
Avoiding common pitfalls
When people start using OSG i, they often write code that looks similar to the following
Listing 4.3 Broken lookup example—service instance stored in a field
public class Activator implements BundleActivator {
LogService m_logService;
Finds single best
Log Service
public void start(BundleContext context) {
ServiceReference logServiceRef =
m_logService = (LogService) context.getService(logServiceRef);
instance in
field (bad!)
Log Service
test thread
public void stop(BundleContext context) {
Because you store the Log Service instance in a field, the test code can be simple:
while (Thread.currentThread() == m_logTestThread) {
m_logService.log(LogService.LOG_INFO, "ping");
But there's a major problem with the bundle activator. The Log Service implementa-
tion is stored directly in a field, which means the consumer won't know when the ser-
vice is retracted by its providing bundle. It only finds out when the implementation
starts throwing exceptions after removal, when the implementation becomes unsta-
ble. This hard reference to the implementation also keeps it from being garbage col-
lected while the bundle is active, even if the providing bundle is uninstalled. To fix
this, let's replace the Log Service field with the indirect service reference, as shown in
the following listing.
Listing 4.4 Broken lookup example—service is only discovered on startup
public class Activator implements BundleActivator {
ServiceReference m_logServiceRef;
BundleContext m_context;
Stores indirect
service reference
public void start(BundleContext context) {
m_logServiceRef =
Search WWH ::

Custom Search