OSGi – not just a four letter word

You may have heard the word OSGi recently: perhaps on a technical blog, or in a passing conversation between developers. In the very near future words like OSGi, bundles, OSGi services and the service registry will be essential concepts that every web application developer and architect should know and understand.

This article introduces OSGi, and presents some sample code and useful design patterns.

So what exactly is OSGi?

OSGi is a dynamic component system for Java where components can be installed,
uninstalled, started, stopped, and updated without restarting the Java runtime. This
means you can safely perform maintenance while users are still using your system.
Applications are composed of one or more components (called bundles) which pro-
vide both encapsulation and controlled sharing of resources using declarative rules.
The OSGi standard has been carefully matured over eight years by an alliance of
companies that includes BEA, IBM, Oracle and Red Hat. But wait, you ask – aren’t
those companies the leading suppliers of application servers? That’s right, and they
are all busy migrating existing and new products to work with OSGi. The OSGi
Alliance[1] is itself updating specifications with additional enterprise features, to
improve support for architectures like SCA.

Basic terminology

OSGi introduces the notion of bundles: a bundle is a collection of classes and re-
sources, along with metadata that gives this collection some identity. This metadata
also describes what it can provide to other bundles (exports) and what it requires
from other bundles (imports), or the framework. A bundle has a well-defined life-
cycle, managed by the OSGi framework. Both bundles, and the individual packages
they import or export can be versioned using standard math notation.

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-SymbolicName: myBundle
Bundle-Version: 1.0.0
Bundle-Activator: org.example.component.internal.Activator
Import-Package: org.example.component;version=
  ”[1.0.0,2.0.0)”, org.osgi.framework;version=1.3
Private-Package: org.example.component.internal
Export-Package: org.example.component;version=1.0.0

Figure 1. Example OSGi metadata from a bundle manifest

Bundles are managed by an OSGi framework[2] [3] [4] [5]. Some frameworks
like Equinox, as used under Eclipse, can handle over 5000 bundles at one time.
Each framework uses carefully crafted classloaders to wire packages and resources
between bundles, according to their metadata. These classloaders don’t follow the
normal parent delegate model. This means you can have different versions of the
same bundle or package working seamlessly inside the same JVM process. You can
also dynamically update, start and stop bundles individually without shutting down
the process, allowing for a true 24×7 level of service.

public class Activator implements BundleActivator
    public void start( BundleContext context ) throws Exception
        // set-up, start any local threads, open trackers

    public void stop( BundleContext context ) throws Exception
        // tear-down, signal threads to stop, close trackers

Figure 2. Bundles wishing to participate in the OSGi lifecycle can provide Bundle-Activator implementations

Fine-grained, dynamic wiring of packages is ideal for application servers, but
OSGi provides another useful feature: the OSGi service registry.

OSGi Services and the Service Registry

In OSGi, services are plain Java objects that are registered in the registry by a bundle,
along with a set of properties. Clients wishing to use services can query the registry
using standard LDAP filter syntax. This lookup takes the bundle metadata into ac-
count, so clients get offered services they can use without causing a ClassCastException.
The OSGi core provides both low-level query and listener APIs for the service
registry. However most people use the ServiceTracker utility class, which provides
general boilerplate code to access services in a guaranteed safe fashion.

m_logTracker = new ServiceTracker(context, LogService.class.getName(),
// get highest ranked compatible service
LogService logService = (LogService) m_logTracker.getService();
// get all compatible services
Object[] logServices = m_logTracker.getServices();

Figure 3. The ServiceTracker provides a simple way to access OSGi services

The OSGi Service Registry has proved to be extremely adaptable, most new
requirements and features such as servlet support are implemented as optional
framework services. The actual core framework remains lean and well-specified: for
example, the Concierge R3 framework is only 80k and works on a range of mobile

Whiteboard Pattern

Over the last few years a couple of patterns have emerged for handling OSGi Serv-
ices. The Whiteboard pattern, so-called because it uses the Service Registry as a form
of whiteboard, is a replacement for the classic Listener pattern. The key benefit of
the Whiteboard pattern is that it requires fewer classes and less supporting code.
For example, imagine a client bundle wants to listen to several data sources. With
the Listener pattern the client would lookup the available data sources and register
a callback with each one. It would have to maintain a list of the sources it had reg-
istered with, so it could unregister itself when it was stopped. Similarly each data
source would have to maintain a list of clients.
However, there’s already code designed to keep track of such things – the OSGi
Service Registry. Using the whiteboard pattern, client bundles register a known serv-
ice with the registry. All the data source now needs to do is query which bundles
have registered this service, and use it to send the data to the client. So client bundles
only need to register once with the registry, and data sources can delegate client management to the Service Registry.

Figure 4

Figure 4. The Whiteboard pattern, compared to the Listener pattern

An example implementation that uses the Whiteboard Pattern can be found on
the OPS4J Community Site[6] under the Pax Web project.

Extender Pattern

Another popular pattern is the Extender pattern, where a bundle keeps track of
other bundles and reacts according to an agreed piece of metadata. This pattern can
be used to extend the OSGi framework for different domains, without causing API
bloat or duplicated code.
A good example of the Extender pattern is servlet registration. The HTTP Serv-
ice API has methods for client bundles to register servlets and resources with the
HTTP Service. However, for a client to use this registration method it must keep
track of which HTTP Services are available. This can lead to the same code being
duplicated in each client.
The Extender Pattern moves the responsibility of registration to a single bundle
(the extender bundle). A servlet extender bundle would watch for other bundles
with metadata detailing servlet implementations, and use this to register servlets on
behalf of other bundles.

Figure 5

Figure 5. The Extender pattern Spring-OSGi

A good example of the Extender pattern can be found in the Spring-OSGi
project[7]. This project was started when Adrian Colyer had a hunch that Spring
and OSGi would make a good match. In less than a year, the latest Spring 2.1 mile-
stone jars have all been enhanced with OSGi metadata and Spring-OSGi is onto it’s
third milestone. Adding support for OSGi has made Spring much more dynamic
and modular.

Spring-OSGi introduces four main bundles:

1. spring-osgi-core – contains the context code, proxies and main logic to bridge
between Spring and OSGi
2. spring-osgi-io – provides access to bundle resources as Spring resources, using
the “bundle:” prefix
3. spring-osgi-extender – detects bundles with Spring metadata, and creates/de-
stroys contexts as necessary
4. spring-osgi-mock – support for dynamically mocking bundles at runtime dur-
ing integration testing

Spring-OSGi uses the new schema support to add an OSGi namespace and sche-
ma[8] which allows Spring Beans to be exported as OSGi services, which can then
be imported by other bundles.

<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”

    <bean id=”weatherService”
        <property name=”weatherDao”>
            <osgi:reference interface=”org.springframework.osgi.samples.wea-

    <osgi:service ref=”weatherService”>
            <entry key=”foo” value=”bar”/>
            <prop key=”baz”>myprop</prop>


Figure 6. Sample XML configuration from the Spring-OSGi weather service sample

You can use this schema to modularize your Spring application, which can then
be deployed as a series of bundles onto an OSGi framework. The dynamic nature
of OSGi, coupled with proxies generated by Spring-OSGi, means you can start and
stop different parts of your Spring application, and even upgrade parts without stop-
ping the main application. It is no surprise that the Spring team is very excited about
OSGi and the possibilities it brings.


This article introduced OSGi, and some of the key concepts and patterns that are
in use today. As shown by its rapid acceptance by Spring, OSGi is a great technol-
ogy for producing dynamic, modularized applications. This is the best time to get
involved and start learning about OSGi, before it becomes an essential skill.


1. OSGi Alliance
2. Equinox OSGi Framework at Eclipse
3. Felix OSGi Framework at Apache
4. Knopflerfish OSGi Framework
5. ProSyst OSGi Framework
6. OPS4J Community Site
7. Spring-OSGi Project
8. Spring-OSGi M3 Schema

Originally published in JayView.

This Post Has One Comment

  1. mikhail

    Cool explanation ) , Thanks

Leave a Reply