Home Tutorial Java Core Java Thread : setContextClassLoader() method

 
 

Share on Google+Share on Google+
Java Thread : setContextClassLoader() method
Posted on: October 20, 2012 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java Thread : setContextClassLoader() method :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 20, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com