YOUR FEEDBACK
Tim FitzGerald wrote: As an HP distributor who specializes in virtualization solutions, we view these...
AJAXWorld RIA Conference
$300 Savings Expire September 5th. Register Today and SAVE!

SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


Demystifying Class Loading Problems
Part Two of a Four-Part Article

This four-part article series examines Java class loading to help application developers understand and debug problems they may encounter. In Part 2, authors Lakshmi Shankar and Simon Burns from the IBM Hursley Labs tackle some exceptions that, while fairly simple, often puzzle novice and experienced Java developers alike.

This article, the second in a series of four, looks at the various class loading exceptions typically thrown when running applications. These exceptions, though commonly seen, are often not well understood by Java developers. Taking each exception in turn, this article provides detailed examples that highlight their behavior, explain their causes, and show some possible resolution techniques. The article starts with the very common ClassNotFoundException and moves onto less well known exceptions, such as ExceptionInInitializerError.

Before you begin this article, you should be familiar with the class loader delegation model, along with the phases and stages of class linking.

ClassNotFoundException
ClassNotFoundException is the most common type of class loading exception. It occurs during the loading phase. The Java specification describes ClassNotFoundException as follows:

Thrown when an application tries to load in a class through its string name using:

  • The forName() method in class Class.
  • The findSystemClass method() in class ClassLoader.
  • The loadClass() method in class ClassLoader.
but no definition for the class with the specified name could be found.

So a ClassNotFoundException is thrown if an explicit attempt to load a class fails. The test case in Listing 1 provides example code that throws a ClassNotFoundException:

Listing 1. ClassNotFoundExceptionTest.java

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class ClassNotFoundExceptionTest {

    public static void main(String args[]) {
      try {
        URLClassLoader loader = new URLClassLoader(new URL[] { new URL(
"file://C:/CL_Article/ClassNotFoundException/")});
        loader.loadClass("DoesNotExist");
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      }
    }
}

This test case defines a class loader (MyClassLoader), which is used to load a non-existent class (DoesNotExist). When it is run, the following exception occurs:

java.lang.ClassNotFoundException: DoesNotExist
      at java.net.URLClassLoader.findClass(URLClassLoader.java:376)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:572)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
      at
ClassNotFoundExceptionTest.main(ClassNotFoundExceptionTest.java:11)

A ClassNotFoundException is thrown because the test attempts the load using an explicit call to loadClass().

By throwing a ClassNotFoundException, the class loader informs you that the bytecode required to define the class is simply not present in the locations where the class loader is looking for it. These exceptions are usually simple to fix. You can ensure that the classpath being used is set as expected by checking it using the IBM verbose option. (For more on this option, see the first article in this series.) If the classpath is set correctly but you're still seeing the error, then the desired class is not present on the classpath. To fix this, either move the class into a directory or JAR file specified in the classpath, or add the location where the class is stored to the classpath.

NoClassDefFoundError
NoClassDefFoundError is another common exception thrown by the class loader during the loading phase. The JVM specification defines NoClassDefFoundError as follows:

Thrown if the Java virtual machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

Essentially, this means that a NoClassDefFoundError is thrown as a result of a unsuccessful implicit class load. The test case in Listings 2 through 4 produce a NoClassDefFoundError because an implicit load of class B will fail:

Listing 2. NoClassDefFoundErrorTest.java

public class NoClassDefFoundErrorTest {
    public static void main(String[] args) {
       A a = new A();
    }
}

Listing 3. A.java

public class A extends B {
}

Listing 4. B.java

public class B {
}

Once you've compiled the code in these listings, remove the classfile for B. When the code is executed, the following error occurs:

Exception in thread "main" java.lang.NoClassDefFoundError: B
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:810)
    at
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:147)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:475)
    at java.net.URLClassLoader.access$500(URLClassLoader.java:109)
    at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:848)
    at java.security.AccessController.doPrivileged1(Native Method)
    at
java.security.AccessController.doPrivileged(AccessController.java:389)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:371)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:572)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:442)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    at NoClassDefFoundErrorTest.main(NoClassDefFoundErrorTest.java:3)

Class A extends class B; so, when class A is being loaded, the class loader implicitly loads class B. Because class B is not present, a NoClassDefFoundError is thrown. If the class loader had been explicitly told to load class B (by a loadClass("B") call, for instance), a ClassNotFoundException would have been thrown instead.

Obviously, to fix the problem in this particular example, class B must be present on the classpath of a suitable class loader. This example may seem trivial and unrealistic; however, in complex, real-world systems with many classes, situations like this can happen when classes are missed during packaging or deployment.

In this example, A extends B; however, the same error would still occur if A referenced B in any other way -- as a method parameter, for example, or as an instance field. If the relationship between the two classes were one of reference rather than of inheritance, then the error would be thrown on the first active use of A, rather than during the loading of A.


About Lakshmi Shankar
Lakshmi Shankar is a Software Engineer in IBM Hursley Labs, UK. He has worked for IBM for more than three years and has a broad range of experience, having worked in Java performance, test, and development within Hursley Labs. Until recently he was the Class Loading component owner for IBM's Java technology. He is now a developer working as part of the Information Management team.

About Simon Burns
Simon Burns was the component owner and team lead for the Persistant Reusable JVM in the Java Technology Centre in IBM Hursley Labs. He worked in JVM development for over three years, specializing in the Persistant Reusable JVM technology and the z/OS platform. He has also worked closely with CICS, helping them to exploit this technology. Simon worked on the OSGi framework as part of the open-source Eclipse Equinox project, which has now been integrated into Eclipse 3.1. He is now working on componentization.

YOUR FEEDBACK
Jan Naude wrote: Relating to Doug Smith's question: Doug, I think you misunderstand MVC. The components are: Model (data retrieved/manipulated by business rules) View (responsible for rendering/displaying relevant information to user) Controller - business logic that operates on/manipulates model to produce data to be displayed by view. The idea with MVC is not to mix business logic (i.e. Servlets/Struts actions) and presentation logic (jsp/html) in the same artifacts (components), because then you end up not being able to replace/change one without having to replace/change the other. JSF focuses more on easily developing the View part, while Struts concentrates more on Model and Controller and their integration.
Jose Arco wrote: Hi, Really interesting article. I have a related question. We have a web acces application based completly on Struts. Now we want to add a new funcionality based on JSF, the question is if we could have integration problems between both tools. Thanks in advanced
bill wrote: it would be nice to redo this comparison TODAY in 2007 and see what comes out. Struts2 has really added a ton to their side and JSF components have matured. I would like to see a modern comparison- as there does not seem to be one.
wildcat wrote: Hi, Yes JSF is the way to go. The thing which I like the most about JSF is the finer control given by the component based architechture which is the key for RAD tools..like .NET. Java is up there facing a string competition form .NET but hey JAVA will WIN.
Doug Smith wrote: Friends, this is going to sound like a really dumb question, but I am asking in all sincerity. While I understand the arguments to separate view (screen) from model (database & rules) & control (keyboard), I'm not sure I understand why I need Struts or JSF to do this. I can put code a View as a JSP, interact with the Model using Javabeans, and exercise Control using HTML or JSP directives. What exactly are the benefits using either Struts or JSF? The cost is obvious - another set of things to learn and configure. (Asked by a solo practitioner who doesn't work with graphic designers).
David Thirakul wrote: Very interesting article, thank you. We are currently working extensively with Struts for the presentation layer and are watching the progress of JSF with much interest because it seems to be the way to go in the long term. There is no doubt that JSF will take over as McClanahan stated himself when he was talking about migrating to JSF. (see http://www.theserverside.com/news/thread.tss?thread_id=29068). There's no new development on Struts as opposed to JSF which by the way is the answer to MS webforms. So to answer Tom's comment, yes there is overlaping and if you start a new project from scratch and want to compare struts and jsf, roland's article is very insightful. What I would like to point out also is that JSF seem to lack the ease of use and functionnality of webforms, that's why all the new development goes into JSF, there's a lot of catching up to do...
Roland Barcia wrote: Thanks for the feedback. Craig has a vested interest in both frameworks. There are features in Struts that compliment JSF like Tiles and the Validation framework. But just because they have some areas where they can work together does not mean I cannot compare them both. In this article, I focus on the Core of the frameworks and how they differ. I see very little benefit with the current Struts implementation to mix the Struts controller with the JSF components.
Tom Roche wrote: To speak of "JSF vs Struts" displays a lack of understanding of the different specializations of the two frameworks. JSF specializes in view, Struts in model and control. The two can be used together via the Struts-Faces Integration Library. As Craig McClanahan's inaugural blog post http://blogs.sun.com/roller/page/craigmcc/20040927#struts_or_jsf_struts_and points out: > For new development, here's the best strategy for determining what > to do: > * Evaluate the two technologies individually, to see if they satisfy > your requirements. > * If one or the other technology is sufficient, go ahead and use it > (it's easier to learn and use one technology rather than two where > possible); keeping in mind, however, the caveats about Struts HTML > tags mentioned above. > * If your requirements include unique features supported only by > Struts (such as Til...
WEBSPHERE LATEST STORIES . . .
Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted to be...
Red Hat CTO Brian Stevens, Citrix CTO Simon Crosby, Egenera CTO Pete Manca, Allen Stewart, Group Manager, Windows Virtualization at Microsoft, and Brian Duckering, Sr. Director of Products and Alliances at Symantec were the top industry executives who joined Jeremy Geelan in the 4th Fl...
IBM announced that Vantage Deluxe World Travel has increased sales and improved business operations since turning to IBM to run its Web site and online booking system. Since switching to IBM WebSphere Commerce software, Vantage Travel has reduced order-taking time by 80 percent and inc...
Mike Neil is general manager for virtualization strategy in the Windows Server Division at Microsoft. Mike is focused on the delivery of the Windows virtualization technology, including Windows Server 2008 Hyper-V, Microsoft Hyper-V Server and Virtual PC 2007. Mike also directs the tec...
The AJAX for IBM WebSphere Platform Early Program is an optionally installable product extension for IBM WebSphere Application Server Version 6.1 and WebSphere Application Server Community Edition that offers targeted, incremental new features that can make Web applications running on ...
Unify announced the expansion of its Composer for Lotus Notes solution through a partnership with CASAHL Technology. Partnering with CASAHL extends the Composer solution to include an assessment of the Lotus Notes infrastructure in order to inventory, categorize and analyze the types o...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING WEBSPHERE NEWS
IBM (NYSE: IBM) today announced it led all vendors worldwide in identity and access management secur...