Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java efficiently search jar files for classes?

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))?

like image 229
mring Avatar asked Jan 07 '10 14:01

mring


2 Answers

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.

like image 145
Pascal Thivent Avatar answered Sep 28 '22 17:09

Pascal Thivent


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.

like image 39
Hassan Syed Avatar answered Sep 28 '22 18:09

Hassan Syed