Java Reference
In-Depth Information
Stateful services
OSGi services don't fit well with the stateful model. The default usage pattern has
only a single service instance for the whole framework, and even if you use a
ServiceFactory , you still only get one instance per client bundle. Added to this,
services have to be thread safe, which becomes much more difficult if they have
state. All in all, we recommend steering clear of stateful services if you can, but
it's perfectly possible to use them if you're careful.
6.4.3
Monitoring the lifecycle
Closely monitoring what's going on with the services you care about is a convenient
way of handling optional services and service multiplicity.
If a service has been declared optional, how do you know if it's there and safe to
use or not? If you have a reference list, how can you know when things magically get
added or removed? If you're interested, you can register service listeners that are noti-
fied when services are registered or unregistered. (If you're not using Blueprint, you
have to care when these things happen. With Blueprint, caring is optional!)
REFERENCE LISTENERS
Reference listeners have a number of potential uses, but you'll start with a straightfor-
ward case—caching. For example, in the Fancy Foods application, the current imple-
mentation of the offer aggregator re-sorts the offer list every time a request is made
(listing 2.11). Users are likely to hit the offer page far more often than the Fancy
Foods business updates its special offers, so caching the sorted list is a performance
optimization.
The code changes to use a cache instead of recalculating the sorted list are
straightforward:
private synchronized void sortOfferList() {
if (offers != null) {
sortedOffers = new ArrayList<SpecialOffer>(offers);
Collections.sort(sortedOffers, new OfferComparator());
int offerCount = Math.min(MAX_OFFERS, sortedOffers.size());
sortedOffers = sortedOffers.subList(0, offerCount);
}
}
@Override
public synchronized List<SpecialOffer> getCurrentOffers() {
return new ArrayList(sortedOffers);
}
The challenge is to know when the cache should be updated, and this is where the ref-
erence listeners come in. Registering a reference listener ensures the OfferAggregator
bean is notified every time an offer is added to or removed from the list. To register
the reference listener, a <reference-listener> declaration is added as a child of the
<reference> or <reference-list> element from listing 2.10:
Search WWH ::




Custom Search