Tutorial :How does Java efficiently search jar files for classes?



Question:

Suppose I have 500 jar files linked to my program totaling over 500 MB (size of all the jars, not each one) and my program makes a call to a class located in one of them. How does Java search through jars for a class, and what is the efficiency of this? O(n)? O(log(n))?


Solution:1

Java looks in the internal directory structure of the jar for an exact match on the fully qualified name. It looks; it does not search. If you have 500 jar files on the classpath, Java will look in them one by one in the specified order until it finds a match. If the jar containing a given class is the last one, Java will look in the 500 jar files. So I guess it's O(n).

UPDATE: The behavior described above is the default behavior. However, as Hassan pointed out, this can be optimized by providing an JarIndex in the root jar file allowing the classloader to find the proper jar file with a simple lookup on a package name.


Solution:2

By default it used to be linear; however, since JDK 1.3 a JAR index can be embedded in the first JAR file of an application.

This means that if the index is embedded into the JAR file the class loader can efficiently find all the classes distributed over multiple JAR files belonging to the application.

link to SUN Resource on JAR Indexing. Note: non-class resources don't seem to be covered.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »