Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use ServiceTracker vs ServiceReference

Tags:

java

osgi

I am just starting with OSGi programming and have come across two ways to listener for services being activated.

The first way, from an EclipseRCP book, uses ServiceReference:

String filter="(objectclass="+IModelCreator.class.getName()+")";
context.addServiceListener(this, filter);
modelCreators = Collections.synchronizedMap(
    new HashMap<ModelID, List<IModelCreator>>());
ServiceReference references[] = context.getServiceReferences(null, filter);
if(references==null) return;
for(int i=0;i<references.length;++i) {
    this.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
        references[i]));
}

The second, from internet examples, uses ServiceTracker:

ServiceTracker logReaderTracker = new ServiceTracker(context,
                org.osgi.service.log.LogReaderService.class.getName(), null);
logReaderTracker.open();
Object[] readers = logReaderTracker.getServices();
if (readers != null) {
        for (int i = 0; i < readers.length; i++) {
        LogReaderService lrs = (LogReaderService) readers[i];
        m_readers.add(lrs);
        lrs.addLogListener(m_logger);
    }
}
logReaderTracker.close();

Which one of these is the correct and/or best way of holding a register of all the services that implement a given Interface? Is there another way of accomplishing this? Why does there seem to be two ways of doing the same thing?

like image 640
KitsuneYMG Avatar asked Nov 17 '09 21:11

KitsuneYMG


1 Answers

As you already can derive form the package name org.osgi.util.tracker.ServiceTracker is ServiceTracker a utility class which (in some cases)

simplifies using services from the Framework's service registry.

In programming there are always several ways of doing things. You either can manage your ServiceReferences by yourself or if it suits you or your problem use the bundled utility class which has its use cases.

Also check this Best practices for accessing services

Some other sources which state that it most of time it is wise to use ServiceTracker

A Comparison of Eclipse Extensions and OSGi Services

OSGi Service Tracker

Getting Started with OSGi: Consuming a Service

like image 79
jitter Avatar answered Sep 23 '22 13:09

jitter