Loader/Launcher – A Pattern to Bootstrap Java Applications

There is still a great number of Java developers out there who are not doing web apps. They use the JDK’s Java launcher directly to bootstrap their apps using public static void main() (abbreviated thereafter as PSVM). And if you are one of those developers, you understand the implications of having a large classpath. It is not uncommon to see shell command with no less than a dozen jars listed on the classpath.

Of course over the years many options have been provided to help with this issue. One of the most recent is from Java 6 where you can reduce the length of the command to launch your Java application by specifying wildcards values in the classpath as shown below:

$ java -cp path1/*.jar:path2:/*:path3/*.jar package.name.ClassName

This write up proposes an alternative approach where your code loads your application’s classes programatically. This pattern, named Loader/Launcher, separates the loading of your application’s classes from the booting of your application logic. The idea is to provide your own loader class that will load your classpath then delegates further bootstrapping responsibilities to a launcher class. One benefit of this approach is that your command to launch your application can be reduced to something like this (no matter the size of your class dependency graph):

$ java -jar package.name.ClassName

The Loader/Launcher Pattern

The way that the Loader/Launcher pattern works is to de-entangle class-loading concerns from application execution concerns. The loading of classes is handled by a Main class with a PSVM method. The native Java command-line launcher loads the Main class. The execution of the application is delegated to a launcher class that implements the Launcher interface. The Launcher is instantiated and invoked by the Main class.

Loader/Launcher Sequence

Loader/Launcher Sequence

To implement this pattern, you will need the following high-level components:

  • The Launcher interface that will be used as a starting point for your app.
  • The Main class where a PSVM method is defined.
  • A Launcher implementation to execute the application.

The Launcher Interface

Implementation of this interface is intended to be the starting point of your application’s bootup process. Instead of starting your application directly in the PSVM method, as is done traditionally, you would relocate the logic for your application’s boot up sequence in a class that implements this interface. When the PSVM method is invoked by the native Java launcher, it would delegate the boot sequence of your application to your Launcher instance (see interface below Listing-1).

 

public interface Launcher {
	public int launch(Object ... params);
}

 

Listing-1

This is a simple interface with a single method, launch(). The method takes an array of objects that can be used to pass in arguments to launcher. The method’s signature makes easy to maintain the semantic of PSVM when using the Launcher.

The Main Class

The Main class is designed to be the starting point for the native Java launcher by exposing a PSVM method. The role of this class, in the Loader/Launcher Pattern, is summed up below:
It creates and loads the application’s classpath. Internally, it instantiates a ClassLoader that is used to load the application’s classpath from a specified location.
Once the classpath is in place, it creates an instance of Launcher, from the classpath, to boot up the application by calling launch().

Listing-2 shows the content of a Main class.

 

public class Main {
	private static String CLASSPATH_DIR = "lib";
	private static String LIB_EXT = ".jar";
	private static String LAUNCHER_CLASS = "demo.launcher.AppLauncher";

	private static ClassLoader cl;
	static{
		try {
			cl = getClassLoaderFromPath(
				new File(CLASSPATH_DIR),
				Thread.currentThread().getContextClassLoader()
			);
			Thread.currentThread().setContextClassLoader(cl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Returns a ClassLoader that for the provided path.
	private static ClassLoader getClassLoaderFromPath(File path, ClassLoader parent) throws Exception {
		// get jar files from jarPath
		File[] jarFiles = path.listFiles(new FileFilter() {
			public boolean accept(File file) {
				return file.getName().endsWith(Main.LIB_EXT);
			}
		});
		URL[] classpath = new URL[jarFiles.length];
		for (int j = 0; j < jarFiles.length; j++) {
			classpath[j] = jarFiles[j].toURI().toURL();
		}
		return new URLClassLoader(classpath, parent);
	}

	public static void main(String[] args) throws Exception{
		Launcher launcher = Launcher.class.cast(
			Class.forName(LAUNCHER_CLASS, true, cl).newInstance()
		);
		launcher.launch(new Object[]{"this string is capitalized"});
	}
}

 

Listing-2

The first thing to notice is the static declarations at the start of the listing. The first three declarations setups the “lib” directory as the location for the classpath, provides “.jar” as the file extension, and specifies demo.launcher.AppLauncher as the name of the Launcher class to load from the classpath. The static code block uses method getClassLoaderFromPath() to initialize a URLClassLoader instance (that points to the lib directory) that will serve as the class loader for the rest of the application.

When the public static void main() method in the Main class is invoked (by the Java launcher), it searches and loads an instance of class demo.launcher.AppLauncher which implements Launcher. Then, the code calls Launcher.launch() to delegate the execution of the rest of the application by passing in a String parameter.

The Launcher Class

The Launcher class is responsible for starting up the application-specific logic. Implementation of the launch() method maintains the same signature as the the PSVM method from the Main class to maintain the familiar semantic. Parameters are passed in as arrays of objects and the method is expected to return an integer. A return value of 0 means everything is OK while anything else means something up to the discretion of the implementor. Listing-3 shows a simple implementation of the Launcher class.

 

public class AppLauncher implements Launcher {
	public int launch(Object ... args) {
		String result = org.apache.commons.lang3.text.WordUtils.capitalize((String)args[0]);
		System.out.println (result);
		return 0;
	}
}

 

Listing-3

How It Works

This implementation uses Apache Commons-Lang to capitalize the value of an argument that was passed in. While this is a simple example, it shows exactly how the pattern would work.  When the application is invoked from the command-line using

$ java -jar demo.launcher.Main

The Main class resolves the classpath by loading jars from the jar directory.  The classpath directory contains all jars that satisfies the dependency graph of the application.  In this example the application depends on the Apache-Commons Lang jar.  When Main instantiates its ClassLoader instance, the jar will be added on the classpath and thus be available for use.

An Example

You can download example code that shows how this works from the location below:
An example – https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher

The example comes in three separate projects:

  • Launcher-Api – contains the definition of the Launcher interface.
  • Launcher-Impl – contains an implementation of the Launcher interface.
  • Laucnher-Main – contains the Main class that is used as the starting point of the application.

Conclusion

The Loader/Launcher Pattern is an attempt to decouple two distinct activities that occur when a Java application is started: that of class loading and and application start up. The pattern uses a Main class as the entry point from the Java native launcher and is used to  load the application’s classpath from a given location.  The act of activating the application is then relegated to a Launcher class.  The launcher is responsible for actually starting up the application-specific logic in the code.  Some of the benefit of adopting this pattern is, firstly, the tighter control over how classes are loaded.  You no longer have to rely on the native Java launcher to resolve your classpath.  Another benefit is the separation of concerns for the start up sequence of the app.  The pattern provides a location, the Launcher interface, where to define what should happen when the application itself (not loading of classpath) is starting.  Hope this was helpful.

Reference

https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher - the example

http://code.google.com/p/clamshell-cli/ - tool that uses this pattern

posted on 2012-10-15 10:37  Xingning Ou  阅读(437)  评论(0编辑  收藏  举报

导航