Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "Context Class Loader Enhancements"

(Overview)
(Overview)
Line 1: Line 1:
 
== Overview ==
 
== Overview ==
<font color="red">'''Note that this is a design that the Equinox team considered proposing to a future OSGi specification.  At this time the design has not been implemented or proposed to OSGi.  None of the new headers defined in this design are supported in Equinox.'''</font>
+
This design defines the behavior of the context class loader in the Equinox OSGi Framework.  Many java libraries exist that use the context class loader.  In an OSGi Framework environment the context class loader is not defined.  This leads to class loading issues when trying to package such libraries into bundles.  This document describes the solutions offered by the Equinox OSGi Framework to solve some of these issues.
This design defines the behavior of the context class loader in the OSGi Framework.  Many java libraries exist that use the context class loader.  In an OSGi environment the context class loader is not defined.  This leads to class loading issues when trying to package such libraries into bundles.
+
  
 
== Terminology ==
 
== Terminology ==

Revision as of 10:52, 4 May 2007

Overview

This design defines the behavior of the context class loader in the Equinox OSGi Framework. Many java libraries exist that use the context class loader. In an OSGi Framework environment the context class loader is not defined. This leads to class loading issues when trying to package such libraries into bundles. This document describes the solutions offered by the Equinox OSGi Framework to solve some of these issues.

Terminology

Context Class Loader

A context class loader is associated with a Thread. This class loader is provided by the thread creator to code running in the thread for the purpose loading classes and resources. This class loader is useful for loading classes and resources that are not always available to the class loader which loaded the code running in the thread.

Context Switch

For the purpose of this design a Context Switch is defined as the point in an execution sequence when a component boundary is crossed from one component to the next.

Class forName

A classic Java mechanism for dynamic class discovery and loading. It uses the current classloader to look for and load the requested class. The current classloader is the classloader that loaded the class containing the method executing the forName(String) call.

Context Finder

A special class loader that finds that first Bundle classloader on that stack and delegates load requests to that classloader.

Buddy Policy

A policy that allows a bundle to declare it needs help from other bundles to load classes. This type of policy does not cause a hard dependency wire to be used to load the classes from a buddy.

Problem Description

Most OSGi-biased developers will concede that the majority of java libraries out there are not currently shipped as OSGi bundles and are not aware of the Modular Layer in the OSGi Framework. Many existing java libraries are designed to run inside a container (J2EE container, Applet container etc). Such containers explicitly define execution boundaries between the various components running within the container. The container controls the execution boundaries and knows when a boundary is being crossed from one component to the next.

This level of boundary control allows a container to switch the context of a thread when a component boundary is crossed. Typically when a container detects a context switch it will set the context class loader on the thread to a class loader associated with the component which is being entered. When the component is exited then the container will switch the context class loader back to the previous context class loader.

The OSGi Framework specification does not define what the context class loader should be set to and does not define when it should be switched. Part of the problem is the Framework is not always aware of when a component boundary is crossed. For some operations the Framework is aware of component boundaries, for example, when calling out to BundleActivators and event listeners. Switching the context class loader when calling out to these types of objects will not solve a large number of usecases.

Consider the following example:

  • Bundle W exports a package “some.foo.library”. This package contains code which uses the context class loader to load additional classes. Imagine it has some SPI like behavior where it loads classes based on some properties file similar to how javax.xml.parsers package works.
  • Bundle X exports a package “some.foo.stuff”. This package contains a service interface “some.foo.stuff.BarService”.
  • Bundle Y imports the “some.foo.stuff” package and registers a “BarService” implementation with the service registry.
  • Bundle Y also imports the “some.foo.library” and expects the exporter to be able to load classes from bundle Y. Bundle Y uses the “some.foo.library” package in its implementation of the “BarService”.
  • Bundle Z imports the “some.foo.stuff” package and gets the “BarService” from the service registry and uses it.

In this scenario imagine the framework sets the context class loader to Bundle Z’s class loader before calling its BundleActivator to start the bundle. In the BundleActivator of Z it gets the BarService if it is available and start making calls to it. At this point code in Bundle Y will get executed because it contains the implementation of the BarService. The implementation of the BarService then uses the package “some.foo.library”. This will cause the code in Bundle W to run that uses the context class loader. At this point the context class loader will be set to Bundle Z’s class loader. This class loader does not have access to the content in Bundle Y and will result in Bundle W’s library code not being able to load classes from Bundle Y.

As a work around to this issue Bundle Y could wrap all calls to code in the package “some.foo.library” with context class loader switches, but this puts a great burden on any developer using the package “some.foo.library”. This also calls into question the purpose of the Framework switching the context class loader at all (to Bundle Z’s class loader in the example above). Any time more than one component boundary is crossed the original context class loader will likely not be the one that is needed.

This design specifies a behavior for the context class loader that should help solve some of these issues.

Requirements

  1. The solution MUST reduce or illiminate the need for code packaged in a bundle to call Thread.setContextClassLoader while calling library code
  2. Library bundles MUST be able to use the context class loader to access classes needed by the library
  3. other reqs ...

Technical Solution

To solve the requirements this design introduces the buddy class loading and context finder concepts


Buddy Class Loading

Buddy class loading offers an integration strategy that does not require modifying the Java code of existing libraries that use the Class.forName(String) approach to dynamically discover and load classes. The mechanism works as follows:

  • A Bundle declares that it needs the help of other bundles to load classes
  • The Bundle identifies the kind of help they need by specifying a buddy policy. The policy defines what kind of bundles will be considered to be buddies.
  • When a bundle class loader fails to find a desired class through the normal OSGi delegation model (i.e. Import-Package, Require-Bundle, and local classpath), its buddy policy is invoked
  • The invoked buddy policy discovers a set of buddies and consults each one in turn until either the class is found or the list is exhausted.

Search Order

The following is a modified class/resource search order:

Frameworks must adhere to the following rules for class or resource loading. When a bundle’s class loader is requested to load a class or find a resource, the search must be performed in the following order:

  1. If the class or resource is in a java.* package, the request is delegated to the parent class loader; otherwise, the search continues with the next step. If the request is delegated to the parent class loader and the class or resource is not found, then the search terminates and the request fails.
  2. If the class or resource is from a package included in the boot delegation list (org.osgi.framework.bootdelegation), then the request is delegated to the parent class loader. If the class or resource is found there, the search ends.
  3. If the class or resource is in a package that is imported using Import-Package or was imported dynamically in a previous load, then the request is delegated to the exporting bundle’s class loader; otherwise the search continues with the next step. If the request is delegated to an exporting class loader and the class or resource is not found, then the search terminates and the request fails.
  4. If the class or resource is in a package that is imported from one or more other bundles using Require-Bundle, the request is delegated to the class loaders of the other bundles, in the order in which they are specified in this bundle’s manifest. If the class or resource is not found, then the search continues with the next step.
  5. The bundle’s own internal bundle class path is searched. If the class or resource is not found, then the search continues with the next step.
  6. Each attached fragment’s internal bundle class path is searched. The fragments are searched in ascending bundle ID order. If the class or resource is not found, then the search continues with the next step.
  7. If the class or resource is in a package that is exported by the bundle or the package is imported by the bundle (using Import-Package or Require-Bundle), then the search ends and the class or resource is not found.
  8. Otherwise, if the class or resource is in a package that is imported using DynamicImport-Package, then a dynamic import of the package is now attempted. An exporter must conform to any implied package constraints. If an appropriate exporter is found, a wire is established so that future loads of the package are handled in Step 3. If a dynamic wire is not established, then the search continues to step 10.
  9. If the dynamic import of the package is established, the request is delegated to the exporting bundle’s class loader. If the request is delegated to an exporting class loader and the class or resource is not found, then the search terminates and the request fails.
  10. If the bundle has declared a buddy policy then the request is delegated to each buddy bundle class loader until either the class or resource is found or all of the buddy bundle class loaders have been delegated too.

When delegating to another bundle class loader, the delegated request enters this algorithm at step 3 and exits at step 9. The buddy policy is not used when delegating to another bundle class loader.

Buddy Policy

A buddy policy defines a policy for selecting buddies that will be used to for buddy class loading. Currently Equinox defines a number of built-in Buddy policies. This design will only descuss two of the possible buddy policies.

  • dependent - Consults all bundles that directly or indirectly depend on the bundle. An indirect dependency can be introduced by bundles that use Require-Bundle with the visibility directive set to reexport. Note that this casts a rather wide net and may introduce performance problems as the number of bundles increase.
  • registered - Consults all bundles that explicitly register themselves as buddies to the bundle.

Bundle-BuddyPolicy Header

The syntax of the Bundle-BuddyPolicy header is the following

Bundle-BuddyPolicy ::= buddy-clause ( ',' buddy-clause )*
buddy-clause ::= loading | participant
 loading ::= 'loading' ';' 'policy' '=' '"' policy ( ',' policy ) * '"'
  policy ::= ('dependent' | 'registered')
 participate ::= 'participate' ( ';' participate-parameter ) *
  participate-parameter ::= (registered | packages)
  registered ::= 'registered' '=' '"' symbolic-name ( ',' symbolic-name ) * '"'
  packages ::= 'packages' '=' '"' package-name ( ',' package-name ) * '"'

The header allows a bundle to declare loading and participation policies. The loading clause is used to declare a bundle needs help from buddy bundles to load classes and resources. One directive is defined to specify the buddy loading policy:

  • policy - A comma-separated list of buddy loading policy names that are to be used for the bundle. Note that the use of a comma in the value requires it to be enclosed in double quotes. Currently only 'registered' and 'dependent' policies are defined

The participate clause is used to declare properties for when a bundle is selected as a buddy of another bundle. The follwing directives are defined for the participate clause:

  • registered - A comma-separated list of symbolic names of bundles that this bundle should be a registered buddy to. Note that the use of a comma in the value requires it to be enclosed in double quotes.
  • packages - A comma-separated list of package names that are to be available to bundles which this bundle is a buddy to. Note that the use of a comma in the value requires it to be enclosed in double quotes.

The following is an example of a Bundle-BuddyPolicy header that defines this bundle needs buddy loading policy of 'registered' and that this bundle is registered as a buddy with the a bundle with the symbolic-name of 'org.acme.somelib' and that only the package 'org.acme.mypackage' is available to bundles which this bundle is a buddy to.

Bundle-BuddyPolicy: 
 loading; policy="registered",
 participate; registered="org.acme.somelib"; packages="org.acme.mypackage"

Context Class Loader

Since Java 1.2, the Class.forName(String) mechanism has been largely superseded by context classloading. As such, most modern class libraries use a context classloader. This section descibes how the use of a context class loader can be transparently converted into something equivalent to Class.forName(String). Doing this allows the buddy loading mechanism described above (and DynamicImport-Package) to be used to eliminate ClassNotFoundExceptions and NoClassDefFoundErrors.

Each Java Thread has an associated context classloader field that contains a classloader. The classloader in this field is set, typically by the application container, to match the context of this current execution. That is, the field contains a classloader that has access to the classes related to the current execution (e.g., Web request being processed). Libraries such as log4j access and use the context classloader with the updated AppenderHelper code pattern below:

public class AppenderHelper {
  private Appender createAppender(String appenderName) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class appenderClass = loader.loadClass(appenderName);
    return (Appender)appenderClass.newInstance();
  }
}

By default, the context classloader is set to be the normal Java application classloader. That is, the use of the context classloader in normal Java application scenarios is equivalent to using Class.forName(String) and there is only one classloader, the application classloader. When running inside the Framework, however, the code pattern outlined above fails because:

  • By default, the Framework does not consult the application classloader. OSGi-based applications put their code in bundles and export particular packages instead of placing all the code on the normal Java application classpath.
  • The Framework cannot detect bundle context switches and set the context classloader as required. That is, there is no way to tell when execution context shifts from one bundle to the next as is done in Web application servers.

These characteristics, combined with the compositional nature of OSGi, mean that the value of the context classloader field is seldom useful.

Clients can, however, explicitly set the context classloader before calling libraries that use the context classloader. The snippet below shows an example of calling log4j using this approach:

Thread thread = Thread.currentThread();
ClassLoader loader = thread.getContextClassLoader();
thread.setContextClassLoader(this.getClass().getClassLoader());
try {
  ... log4j library call that calls AppenderHelper.createAppender() ...
} finally {
  thread.setContextClassLoader(loader);
}

First the current context classloader is saved. The context classloader is then set to an appropriate value for the current execution and log4j is called. log4j’s AppenderHelper uses the context classloader, so in this case, it uses the client’s classloader (e.g., this.getClass().getClassLoader()). When the operation is finished, the original context classloader is restored.

The assumption here is that the client’s classloader is able to load all required classes. This may or may not be true. Even if it can, the coding pattern is cumbersome to use and hard to maintain for any significant number of library calls. Ideally, log4j would be able to dynamically discover the context relevant to a particular classloading operation. The 'context finder' enables this.

Context Finder

The context finder is a kind of ClassLoader that is installed by the Framework as the default context classloader. When invoked, it searches down the Java execution stack for a classloader other than the system classloader. In the AppenderHelper example above, it finds the log4j bundle’s classloader (the one that loaded AppenderHelper). The context finder then delegates the load request to the discovered classloader.

This mechanism transforms log4j’s call to getContextClassLoader().loadClass(String) to the equivalent Class.forName(String) call using log4j’s classloader to load the given class. Now the buddy classloading techniques can be applied to help log4j load the needed appender classes.

The net effect is that clients of log4j do not have to use the cumbersome coding pattern outlined above even though the libraries they call use the context classloader. This approach generalizes to other context classloading situations.

Back to the top