0

The following code is from java.sql.DriverManager:

public static Connection getConnection(String url,String user, String password)    {
    // Gets the classloader of the code that called this method, may 
    // be null.
    ClassLoader callerCL = DriverManager.getCallerClassLoader();
    return (getConnection(url, info, callerCL));
 }

My first question is why the result value of DriverManager.getCallerClassLoader(); may be null? I think the caller Class should be user's own Class, and it is usually AppClassLoader.

The subsequence of above code getConnection(url, info, callerCL), and the method body contains following code snippet.

if(callerCL == null) {
    callerCL = Thread.currentThread().getContextClassLoader();
}    

What's Thread.currentThread().getContextClassLoader() for? I have gone through the document and can't understand it.

Thanks.

Jonathan
  • 20,053
  • 6
  • 63
  • 70
liam xu
  • 2,892
  • 10
  • 42
  • 65

1 Answers1

0

To answer your first question,

why the result value of DriverManager.getCallerClassLoader(); may be null?

It because, if you see the way its defined in class DriverManager

/* Returns the caller's class loader, or null if none */
    private static native ClassLoader getCallerClassLoader();

Its a native method and null value can returned.

To answer your second question:

What's Thread.currentThread().getContextClassLoader() for?

Every thread has a classloader associated with it. If the thread is a main thread then the class loader associated with it a System Class Loader.

Many a times you create an object by one class loader and this object can be potentially used by a thread started by some other class loader. So getContextClassLoader() lets you access a class loader which not the one which loaded the object and can access the resources available to the Thread's class loader.

Here is another thread on the same forum elaborating more on the same topic.

Community
  • 1
  • 1
Santosh
  • 17,667
  • 4
  • 54
  • 79