Read why David Petersheim advocates making sealed jars part of your deployment system. Also, see how sealing your jars may help you solve some classpath problems.
The classpath causes many Java-induced headaches. One of the problems with the classpath is that multiple versions of the same class or classes can be in the classpath at the same time. The virtual machine will load the first one it finds. There are times in which you cannot avoid this situation, such as when your application is running in a container. Sealed jars offer a partial remedy for this problem.
When you use sealed jars in your application, the class loader will ensure that all classes in the same package load from the same jar file. For example, say that class com.acme.A loads from the sealed file acme.jar. Later, the class loader is told to load the class com.acme.B. Since A and B are in the same package, the class loader attempts to load class B from acme.jar. If class B cannot be found in acme.jar but can be found elsewhere, then a SecurityException is thrown.
Sealing a jar is as simple as providing an entry in the jar's manifest file. To create a sealed jar that contained all of the classes in the com directory and its subdirectories package, here's how the command would look:
jar cmf mymanifest.txt myjar.jar com
where mymanifest.txt contains:
The whole jar is now considered sealed by the class loaders that use it.
Sealing your jars won't solve all of your classpath problems, but it can be helpful. This is also a good habit to develop, so start making sealed jars part of your deployment system. There are more options for sealing; for instance, you can seal some packages and not others.
Delivered each Thursday, our free Java newsletter provides insight and hands-on tips you need to unlock the full potential of this programming language. Automatically sign up today!