Java Reference
In-Depth Information
packages are required to be present when resolving dependencies. For optional
imports, this is the whole point: they're optional. For dynamic imports, they aren't
necessarily optional; but because they aren't known in advance, it's not possible for
the framework to enforce that they exist.
Because the packages may not exist in either case, the logical consequence is that
the code in any bundle employing either mechanism must be prepared to catch
ClassNotFoundException s when attempting to access classes in the optionally or
dynamically imported packages. This is typically the sort of issue the OSG i framework
tries to help you avoid with explicit dependencies; we shouldn't be dealing with class-
loading issues as developers.
DIFFERENCES
By now, you must be wondering what the difference is between optional and dynamic
imports. It has to do with when the framework tries to resolve the dependencies.
The framework attempts to resolve an optionally imported package once when the
associated bundle is resolved. If the import is satisfied, the bundle has access to the
package. If not, the bundle doesn't and will never have access to the package unless
it's re-resolved. For a dynamically imported package, the framework attempts to
resolve it at execution time when the bundle's executing code tries to use a class from
the package.
Further, the framework keeps trying to resolve the dynamically imported package
each time the bundle's executing code tries to use classes from it until it's successfully
resolved. If a bundle providing the dynamically imported package is ever deployed
into the executing framework, the framework eventually will be able to resolve it.
After the resolve is successful, the bundle is wired to the provider of the package; it
behaves like a normal import from that point forward.
Let's look at how you can use these mechanisms in a logging example, which is
often an optional activity for bundles.
5.2.4
Logging example
The OSG i specification defines a simple logging service that you may want to use in
your bundles, but you can't be certain it will always be available. One way to deal with
this uncertainty is to create a simple proxy logger that uses the logging service if avail-
able or prints to standard output if not.
Our first example uses an optional import for the org.osgi.service.log pack-
age. The simple proxy logger code is shown here.
Listing 5.1 Simple proxy logger using optional import
public class Logger {
private final BundleContext m_context;
private final ServiceTracker m_tracker;
public Logger(BundleContext context) {
m_context = context;
m_tracker = init(m_context);
 
Search WWH ::




Custom Search