Home Tutorial Java Core Java Thread : setContextClassLoader() method

 
 

Java Thread : setContextClassLoader() method
Posted on: October 20, 2012 at 12:00 AM
In this section, we will discuss about ContextClassLoader with example.

Java Thread : setContextClassLoader() method

In this section, we will discuss about ContextClassLoader with example.

ClassLoader :

In java thread you can use ClassLoader to find the classes. You can set context class loader by using method Thread.setContextClassLoader() method. With the help of ClassLoader you can call getSystemClassLoader() method to get the contextClassLoader. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the  appropriate class loader to code running in the thread when loading classes and resources.

public void setContextClassLoader(ClassLoader cl) : It sets the context ClassLoader for the given Thread. It is set at the time of Thread creation.
It permits the creator of the thread to provide the appropriate class loader to code running in the thread when loading classes and resources.
It throws SecurityException exception.

public ClassLoader getContextClassLoader() : This method returns the context ClassLoader for the given Thread.
It throws SecurityException exception.

Example :  In this example we are using getContextClassLoader() method and setContextClassLoader() method.

public class SetContextLoader implements Runnable {

	Thread thread;

	public SetContextLoader() {
		thread = new Thread(this);
		thread.start();
	}

	public void run() {
		ClassLoader classLoader = thread.getContextClassLoader();
		/* Sets the context ClassLoader for this Thread. */
		thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
		System.out.println("Class - " + classLoader.getClass());
		System.out.println("Parent- " + classLoader.getParent());
	
	}

	public static void main(String args[]) {
		new SetContextLoader();
	}
}

Output :

Class - class sun.misc.Launcher$AppClassLoader
Parent- sun.misc.Launcher$ExtClassLoader@757aef

Related Tags for Java Thread : setContextClassLoader() method :


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.