Miles to go …

April 29, 2010

TOTD #131: Dynamic OSGi services in GlassFish – Using ServiceTracker

Filed under: frameworks, glassfish — arungupta @ 6:54 am

OSGi is the dynamic module system for Java. Each module, or bundle as called in OSGi terminology, is packaged as a JAR file and the inbound and outbound dependencies are explicitly defined using the META-INF/MANIFEST.MF in the JAR file. A complex software system may be broken into multiple modules where each module may be exposing a set of services. These services are then consumed by some other "client" OSGi bundles. The beauty of dynamic nature of OSGi is that each bundle can be easily updated without restarting the framework and any reference to the service in the "client" bundles is also updated accordingly. However the client needs to ensure that they are watching out for changes in the lifecycle of "service" bundle.

GlassFish’s modular architecture is based upon OSGi. The different capabilities such as Web container, EJB container, and RESTful Web services are provided as OSGi modules. The OSGi framework is available to developers as well so that they can construct their application as OSGi modules and leverage all the goodness.

This Tip Of The Day (TOTD) explains an OSGi design pattern that allows the client to track the dynamic discovery of an OSGi service. This means that client keeps a reference to the service which is automatically refreshed if the bundle providing the service is refreshed. And of course, it uses GlassFish to deploy the bundles :-)

For those, who prefer to see the results directly, download and unzip this zip file:

  1. Give the following command in the root directory:

    mvn clean install
  2. Copy the generated bundles to "domains/domain1/autodeploy/bundles" directory as:

    cp helloworld-api/target/helloworld-api-1.0-SNAPSHOT.jar \
    helloworld-impl/target/helloworld-impl-1.0-SNAPSHOT.jar \
    helloworld-client/target/helloworld-client-1.0-SNAPSHOT.jar \

    The following log messages will be displayed in the console:

    services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
    services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#]
    services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
    services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#]

    The log messages from the client bundle invoking the service bundle are highlighted in bold.

  3. Update the service implementation

    1. Edit service implementation in "hello-impl/src/main/java/org/samples/osgi/helloworld/impl/" and change the "return" statement from:

      return "Hello " + name;


      return "Howdy " + name;
    2. Create the service implementation bundle again by giving the command:

      mvn clean install

      in the "helloworld-impl" directory.

    3. Copy the updated bundle from "helloworld-impl/target/helloworld-impl-1.0-SNAPSHOT.jar" to "glassfishv3/glassfish/domains/domain1/autodeploy/bundles" directory. The following sequence of log messages will be seen:

      services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
      services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#]
      /autodeploy/bundles/, felix.fileinstall.filename=org.apache.felix.fileinstall-autodeploy-bundles.cfg,
      service.factorypid=org.apache.felix.fileinstall, felix.fileinstall.debug=1};|Updated
      services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
      services.impl|_ThreadID=23;_ThreadName=Thread-23;|Howdy Duke|#]

      As evident from the log messages, "Hello Duke" message is printed first, the service implementation bundle gets refreshed, and then the message from the updated service implementation, i.e. "Howdy Duke" is printed. Notice, only the service implementation got refreshed.

Now some explanation!

The application is split into 3 bundles – API, Impl, and Client. Splitting into 3 bundles allows cleaner separation and other implementations of the service  to show up relying purely upon the API bundle.

The "API" bundle (helloworld-api) has one class with the following interface:

package org.samples.osgi.helloworld.api;

public interface Hello {
    public String sayHello(String name);

This bundle has the following manifest entry:


to ensure that the package with the service interface is exported and available for imports by service implementers. The "Impl" bundle (helloworld-impl) has the trivial implementation of this interface as:

package org.samples.osgi.helloworld.impl

import org.samples.osgi.helloworld.api.Hello;

public class HelloImpl implements Hello {
    public String sayHello(String name) {
        return "Hello " + name;

And the bundle’s activator registers the service as:

package org.samples.osgi.helloworld.impl;

import java.util.Properties;
import org.samples.osgi.helloworld.api.Hello;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class App implements BundleActivator {

    public void start(BundleContext bc) throws Exception {
        bc.registerService(Hello.class.getName(), new HelloImpl(), new Properties());

    public void stop(BundleContext bc) throws Exception {

This bundle defines the dependency on the package exported earlier as:


and also imports the appropriate packages as:

<Import-Package>${pom.groupId}.api, org.osgi.framework</Import-Package>

The "client" bundle’s (helloworld-client) activator uses "org.osgi.util.tracker.ServiceTracker" for the dynamic discovery of service. The code looks like:

package org.samples.osgi.helloworld.client;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.samples.osgi.helloworld.api.Hello;

public class App implements BundleActivator {
    BundleContext ctx;
    ServiceTracker tracker;

    public void start(BundleContext context) {
        System.out.println("Starting client bundle");

        this.ctx = context;        

        // Create a service tracker to monitor Hello services.
        tracker = new ServiceTracker(context, Hello.class.getName(), null);;

        new PingService(tracker).start();

    public void stop(BundleContext context) {
        System.out.println("Stopping client bundle");

    private class PingService extends Thread {
        ServiceTracker tracker;

        PingService(ServiceTracker tracker) {
            this.tracker = tracker;

        public void run() {
            try {
                while (true) {
                    System.out.println("Getting a new service");
                    Hello hello = (Hello) tracker.getService();
                    if (hello == null)
                        System.out.println("No service found!");
            } catch (InterruptedException ex) {

The ServiceTracker API allows customized service tracking and find services that meet search criteria defined by filters. Basically it listens to different service events and gets/ungets the service accordingly. In this case, a "ServiceTracker" is created to track the service by specifying the class name. The "" starts the service tracking. A new thread is started which pings the service every 2 seconds and prints the received response. Notice, a new service is retrieved from the service tracker as the service bundle might have been refreshed.

Please read through OSGi javadocs for more details on these APIs.

A future blog will show how a Java EE 6 MVC-based application can be split into multiple OSGi bundles using this design pattern.

How are you using dynamic discovery of services in OSGi ?

Technorati: totd osgi modules glassfish v3 felix dynamic discovery

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot
Related posts:
  1. TOTD #124: OSGi Declarative Services in GlassFish – Accessed from a Java EE client
  2. TOTD #130: Invoking a OSGi service from a JAX-WS Endpoint – OSGi and Enterprise Java
  3. TOTD #125: Creating an OSGi bundles using NetBeans and deploying in GlassFish
  4. TOTD #118: Managing OSGi bundles in GlassFish v3 – asadmin, filesystem, telnet console, web browser, REST
  5. TOTD #36: Deploy OSGi bundles in GlassFish using maven-bundle-plugin

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.
Powered by WordPress