Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How JVM starts looking for classes?

  • I was curious about what all locations JVM looks for executing a program? I'm more interested in understanding in what sequence and where does JVM look for class files, like does it look into java libs, extension libs, classpath any directory like the current directory from where the java is invoked? I'm more interested in JVM behaviour and not how class loader load class, which I know has parent delegation mechanism till root.

  • If a class is executed from directory where the compiled class is kept on file system and also in a jar file in the same directory, would JVM load both or just one and which one?

  • Say you have a thread unsafe Vector and if we compare it performance to ArrayList, which one would be better and why?

like image 388
Taran Singh Avatar asked Jan 19 '12 23:01

Taran Singh


2 Answers

How classes are found. Answer is here:

http://docs.oracle.com/javase/1.5.0/docs/tooldocs/findingclasses.html

Answer for point 2: Order of finding classes is as follows:

  1. classes or packages in current directory.
  2. classes found from CLASSPATH environment variable. [overrides 1]
  3. classes found from -classpath command line option. [overrides 1,2]
  4. classes found from jar archives specified via -jar command line option [overrides 1,2,3]

So if you use -jar option while running, classes come from jarfile.

Only one class is loaded though.

like image 152
Rajendran T Avatar answered Oct 16 '22 04:10

Rajendran T


Without using any additional classloader:

  • Search order for a JVM:
    1. Runtime classes (basically, rt.jar in $JRE_HOME/lib`)
    2. Extension classes (some JARs in $JRE_HOME/lib/ext`)
    3. Classpath, in order. There are four possibilities for specifying classpath:
      1. If -jar was specified, then that JAR is in the classpath. Whatever classpath is declared as classpath in META-INF/MANIFEST.MF is also considered.
      2. Else, if -cp was specified, that is the classpath.
      3. Else, if $CLASSPATH is set, that is the classpath.
      4. Else, the current directory from which java has been launched is the classpath.
      So, if I specify -cp src/A.jar:src/B.jar, then A.jar will be searched first, then B.jar
  • The JVM loads only the class that is found first, according to the order in which the directories/JARs are declared in the classpath. This is important if you use -cp or $CLASSPATH.
  • In single thread scenarios and with recent JVMs, Vector and ArrayList should have similar performance (ArrayList should perform slightly better as it is not synchronized, but locking is fast currently when there is no contention, so the difference should be small). Anyway, Vector is obsolete: don't use it in new code.
like image 30
gpeche Avatar answered Oct 16 '22 04:10

gpeche