Fix Pack 8550

Using OSGi services

Services can be registered and unregistered asynchronously at any time. Therefore you should call a service for as short a time as possible. You can use the ServiceTracker class to track service availability concurrently.

About this task

If you want to track services, you can create a ServiceTracker object by using your bundle context, the interface you want, and the properties you want to match, and then open the tracker. You can query the tracker for the best match or all matches. Make sure that you do not occupy the service after you use it. You do not have to tell the tracker you are done; the tracker caches the matching services internally, and clears them as they are unregistered. When you have finished using the tracker, use the serviceTracker.close() method to close it.

Example

The following example shows how to use a ServiceTracker object to track a service:

package com.ibm.foo.tracker;

import com.ibm.foo.simple.Foo;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

/**
 * Simplest use of a ServiceTracker to get a service
 */
public class TrackingFooUser
{

    private ServiceTracker<Foo,Foo> serviceTracker;

    public TrackingFooUser( BundleContext bundleContext )
    {
        serviceTracker = new ServiceTracker<Foo, Foo>( bundleContext, Foo.class, null );
        serviceTracker.open();
    }

    public void doFoo() {
        Foo foo = serviceTracker.getService();
        //use foo
        //no need to return it... just don't use it for long.
    }

    public void shutdown() {
        serviceTracker.close();
    }
}

Icon that indicates the type of topic Task topic

Terms and conditions for information centers | Feedback


Timestamp icon Last updated: Monday, 21 April 2014
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=phil&product=was-nd-mp&topic=twlp_feat_service_tracker
File name: twlp_feat_service_tracker.html