user5182503
user5182503

Reputation:

What services does ServiceTracker find

Let's assume that we have two bundles - BundleA and BundleB. BundleA contains one service. BundleB contains ServiceTracker.

It seems to me, that ServiceTracker in bundleB will find service of BundleA only if bundleB is started before BundleA. By other words, ServiceTracker doesn't find services that were registered before ServiceTracker.open(). Is this right? P.S. I see this behavior on Apache Felix.

EDIT As I was said that my statement was wrong here is my code. BundleA - pax-logging-service. In bundleB I have the following code:

public class PaxLoggingServiceCustomizer implements ServiceTrackerCustomizer<Object, Object>{

    private final BundleContext context;

    public PaxLoggingServiceCustomizer(BundleContext context) {
        this.context=context;
    }

    @Override
    public Object addingService(ServiceReference<Object> reference) {
        System.out.println("# Service was added");
        ManagedService paxService = (ManagedService)context.getService(reference);
        return paxService;
    }

    @Override
    public void removedService(ServiceReference<Object> reference, Object service) {
    }

    @Override
    public void modifiedService(ServiceReference<Object> reference, Object service) {
        //do nothing
    }    

}

And this is bundleB activator

public class Activator implements BundleActivator {

    private ServiceTracker serviceTracker;

    public void start(BundleContext context) throws Exception {
        String f = "(&(service.pid=org.ops4j.pax.logging)(objectClass=" + ManagedService.class.getName()+"))";
        Filter  filter=FrameworkUtil.createFilter(f);
        serviceTracker=new ServiceTracker(context,filter, new PaxLoggingServiceCustomizer(context));
        serviceTracker.open();
    }

    public void stop(BundleContext context) throws Exception {
        serviceTracker.close();
    }

}

When I start bundleB (mybundle) before bundleA (pax-logging-service) - everyhing works and service is added (I see # Service was added message). When I start bundleB (mybundle) after bundleA (pax-logging-service) - nothing works and service is never added (I don't see see # Service was added message even after one minute).

Upvotes: 0

Views: 196

Answers (1)

Marcel Offermans
Marcel Offermans

Reputation: 3323

That is not correct. When you open a service tracker it will immediately see all services that are available in the service registry. If you suspect you are not seeing a service, even though it is registered, it might be because it's not visible to your bundle (because of how the bundles got resolved and wired in the framework).

Upvotes: 2

Related Questions