Java Reference
In-Depth Information
case ServiceEvent.MODIFIED:
break;
Nothing
to do
case ServiceEvent.UNREGISTERING:
m_logService = null;
break;
Stops using service
(see a problem?)
default:
break;
}
}
}
It's safe to call the getService() method during the REGISTERED event, because the
framework delivers service events synchronously using the same thread. This means
you know the service won't disappear, at least from the perspective of the framework,
until the listener method returns. Of course, the service could still throw a runtime
exception at any time, but using getService() with a REGISTERED event always returns
a valid service instance. For the same reason, you should make sure the listener
method is relatively short and won't block or deadlock; otherwise, you block other ser-
vice events from being processed.
REGISTERING A SERVICE LISTENER
You have the service listener, but how do you tell the framework about it? The answer
is, as usual, via the bundle context, which defines methods to add and remove service
listeners. You must also choose an LDAP filter to restrict events to services implement-
ing the Log Service; otherwise, you can end up receiving events for hundreds of differ-
ent services. The final code looks like the following listing.
Listing 4.9 Broken listener example—existing services aren't seen
public class Activator implements BundleActivator {
Threads
access field
BundleContext m_context;
volatile LogService m_logService;
public void start(BundleContext context) throws Exception {
m_context = context;
String filter = "(" + Constants.OBJECTCLASS + "=" +
LogService.class.getName() + ")";
context.addServiceListener(new LogListener(), filter);
startTestThread();
}
public void stop(BundleContext context) {
stopTestThread();
}
}
The LDAP filter matches LogService instances, and you add a listener for future Log
Service events. Notice that you don't explicitly remove the service listener when you
stop the bundle. This is because the framework keeps track of what listeners you've
 
Search WWH ::




Custom Search