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

About these ads
Tags:

7 Comments to “Loader/Launcher – A Pattern to Bootstrap Java Applications”

  1. Hello there !
    Thanx for this nice framework….creating my own CL-tools have been on my mind in a few months now, your framework takes away all the hassles so I can focus on making something that is answer my problems.
    I have however a few question: Sorry if there is a dedicated forums that I missed for that

    -What is the exact role of descriptor.getArguments(). Is it used for argument input vérification, is it only informative? By looking ot JMX-Cli, my old school way of validating input seems ugly to me.
    -Is there anyway to implement a CTRL+X type of input that would break the running command without existing the JVM?
    -How can I display results as they come by? I wrote a command tha ping a range of IP althout the console.writeOutput is whithin the loop, the result appear only in the end.
    -How can I ignore carriage return if it is contained in an argument so it is not interpreded as “hit enter”
    -Is it possible to creat sub-controllers?
    example you have a bunch of command that you want to organize functionnally. and you enter the network controller by typing “cd network”?

    thanx for your work and your help and again… sorry if i missed a support forum?

    • Thanks for using the CLI tool. See answers below:

      -What is the exact role of descriptor.getArguments(). Is it used for argument input vérification, is it only informative? By looking ot JMX-Cli, my old school way of validating input seems ugly to me.

      A: the CLI doesnt force you to use any argument validation. You are free to process as you see fit. The default impl uses JCommander. Jmx-Cli uses json-formatted argument, etc. descriptor.getArguments() is collection of arguments as collected from the command-line.

      -Is there anyway to implement a CTRL+X type of input that would break the running command without existing the JVM?

      A: Currently, that is not automatic. You could create an InputController to catch Ctrl+X and take appropriate action.

      -How can I display results as they come by? I wrote a command tha ping a range of IP althout the console.writeOutput is whithin the loop, the result appear only in the end.
      A: this would require a more sophisticated approach. Currently, if you have a command that hangs the cli thread, you won’t see result until work is done. If you want to see things as they are done, you could spawn a new thread in your Command class. As results comes in, do a console.writeOutput.

      -How can I ignore carriage return if it is contained in an argument so it is not interpreded as “hit enter”
      A: Again, if you want these type of behaviors, it’s best to create your own InputController. Then you can override the default behavior of input -> CRLF -> processing.

      -Is it possible to creat sub-controllers?
      example you have a bunch of command that you want to organize functionnally. and you enter the network controller by typing “cd network”?
      A: Yes, clamshell-cli is designed to be fully expandable.

      See site for more documentation – http://code.google.com/p/clamshell-cli/

  2. Hi,

    i tried to use this launcher pattern, but it`s seems not working correctly, i use your example to run i got this error:
    $ Exception in thread “main” java.lang.NoClassDefFoundError: demo/launcher/api/Launcher
    at demo.launcher.Main.main(Main.java:44)
    Caused by: java.lang.ClassNotFoundException: demo.launcher.api.Launcher
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    … 1 more

    my folder structure is below:
    boot.jar
    lib
    startup.sh (java -jar boot.jar demo.launcher.Main)

    it`s not working standalone but working in IDE(eclipse) , how`s this thing happen?

    do you have any ideas about this issue? thank you!

  3. i already putted the jar file into lib:
    commons-lang3-3.0.1.jar
    launcher-api.jar
    launcher-app.jar

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: