YOUR FEEDBACK
the usr wrote: So... how about your prediction that SCO would prevail? 11/20/2008 565 - FINAL...
Cloud Computing Conference
November 19-21 San Jose, CA
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.

WEBSPHERE LATEST STORIES . . .
IBM is going to buy Transitive, the British cross-platform virtualization firm that salvaged legacy Macintosh programs and made Apple's move from IBM to Intel chips as graceful as a prima ballerina’s pirouette. Transitive is clever at running applications written for one kind of micr...
Emulex has announced that its LightPulse LP21000 family of Fibre Channel over Ethernet (FCoE) Converged Network Adapters (CNAs) have been tested and found to be compatible for use with IBM Systems x3650(7979), x3655(7943) and x3755(7163) series servers. Emulex CNAs enable the consolida...
Mark Papermaster, the ex-VP of blade development at IBM and the guy that IBM stopped from going to Apple to run its iPod and IPhone development on the strength of the non-compete he signed, has sued his former master looking for a declaratory judgment in his favor.
A round-up of the many themes and topics of interest to infrastructure architects, developers and IT managers featuring at SYS-CON's Cloud Computing Expo being held November 19-21, 2008 at The Fairmont Hotel in San Jose, California. The conference is expecting a record turnout of senio...
Okay, here's the deal. When you observe the big software guys and see how quickly they adopt emerging technologies, which will change IT the way we know it today, here is what we see. Larry Ellison invested millions in old SaaS / cloud companies, which gave him zippo in return, and he ...
"More than a half dozen conferences and events targeting Virtualization and Cloud Computing canceled in the past two months," said Fuat Kircaali, CEO of SYS-CON Media. "We predicted that this would be the outcome for many competing shows due to the current economic conditions," he adds...
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
A new report, announced today, found that IBM (NYSE: IBM) supercomputers already deemed the most pow...