views:

216

answers:

4

I have a web application and two class files,

First class is MyClass.class which is inside the abc.jar file (WEB-INF/lib/abc.jar) and Second class is YourClass.class which is inside classes folder (WEB-INF/classes/ YourClass.class).

My question is which class would load first when the Application starts? And Why ?

+3  A: 

Sun's class loader docs always say WEB-INF/classes OR WEB-INF/lib, but doesn't say which one will be checked first.

From IBM docs:

"The rules for loading classes are spelled out in detail in the JVM specification. The basic principle is that classes are only loaded when needed (or at least appear to be loaded this way -- the JVM has some flexibility in the actual loading, but must maintain a fixed sequence of class initialization). Each class that gets loaded may have other classes that it depends on, so the loading process is recursive."

So I think the answer is: It depends on which classes is needed in your application first.

duffymo
+8  A: 

In my experience you can't predict the order in which the classes are loaded by the JVM.

Once I made a test runner (kinda Maven's Surefire) and with the same JVM and OS it loaded classes in different order when run in different machines. The lesson learnt:

You shouldn't build your applications to depend on class loading order

victor hugo
+1 - Excellent point, well written.
duffymo
+1  A: 

As duffymo points out, this can vary. One way you might ascertain the sequence for this specific app is to insert Response.Write text in the class constructors and web web app page loading methods. "Instantiated object in Class A", "Opened web page MyPage", and so on.

Once you've figured out the sequence, comment out the code for those so you can reuse them later to verify that you haven't made a change (such as instantiating an object earlier or later) that affected the sequence.

DOK
+5  A: 

Classes are loaded as needed, for some definition of "needed". Exactly when a class is loaded is dependent upon the JRE implementation, javac implementation, exactly what thread are up to, server code and, of course, application code. It's a bad idea to make assumptions in this area. If you want to see what happens for a particular run, you can use -verbose:class

Tom Hawtin - tackline