Java Reference
In-Depth Information
Threading
OSGi is designed around the normal Java thread abstraction. Unlike other, more
heavyweight frameworks, it assumes that you do your own thread management. You
gain a lot of freedom by doing this, but at the same time you have to make sure your
programs are correctly synchronized and thread safe. In this simple example, nothing
special is needed; but in general, it's likely that stop() will be called on a different
thread than start() (for this reason, you make the member at B volatile ).
The OSGi libraries are thread safe, and callbacks are normally done in a way to give
you some guarantees. For example, in the case of the bundle activator, start() and
stop() are guaranteed to be called in order and not concurrently. So, technically, in
this particular case the volatile might not be necessary, but in general your code
must take thread visibility into account.
the stop() method, which will cause the bundle to freeze. We'll cover these and other
advanced use cases later. In general, if you use threads in your bundles, do so in such
a way that all threads are stopped when the stop() method returns.
Now you've seen how you can handle starting and stopping a bundle, but what if
you want to interact with the OSG i framework? We'll now switch the focus to the
BundleContext object passed into the start() and stop() methods of the activator;
this allows a bundle to interact with the framework and manage other bundles.
BUNDLE CONTEXT
As you learned in the previous section, the framework calls the start() method of a
bundle's activator when it's started and the stop() method when it's stopped. Both
methods receive an instance of the BundleContext interface. The methods of the
BundleContext interface can be roughly divided into two categories:
The first category is related to deployment and lifecycle management.
The second category is related to bundle interaction via services.
We're interested in the first category of methods, because they give you the ability to
install and manage the lifecycle of other bundles, access information about the frame-
work, and retrieve basic configuration properties. This listing captures these methods
from BundleContext .
Listing 3.2 BundleContext methods related to lifecycle management
public interface BundleContext {
...
String getProperty(String key);
Bundle getBundle();
Bundle installBundle(String location, InputStream input)
throws BundleException;
Bundle installBundle(String location) throws BundleException;
Bundle getBundle(long id);
Bundle[] getBundles();
Search WWH ::




Custom Search