0

I have two modules in my application. These modules share some common JARs which contain some static HashMaps. I want these modules to be loaded using different Class Loaders. Each Class Loader will have a custom class path that contains a set of locations.

URL [] urlsForModule1=getURLsForModule1();

URL[] urlsForModule2=getURLsForModule2();

Thread.currentThread().setContextClassLoader( new URLClassLoader( urlsForModule1, ClassLoader.getSystemClassLoader().getParent() ) );
//Perform the activities needed for Module 1
String valueForModelue1=CommonClass.getValueFromMap("someKey");
//The value is already set in some other place and this should give a specific value for Module 1

Thread.currentThread().setContextClassLoader( new URLClassLoader( urlsForModule2, ClassLoader.getSystemClassLoader().getParent() ) );
//Perform the activities needed for Module 2
String valueForModelue2=CommonClass.getValueFromMap("someKey");
//The value it should give a specific value for Module 2

But the problem that I'm facing is with the common Class files which are there in the Common JARs. Since these Class files are already loaded (before the above lines of code in some other classes) the staic HashMaps retain their previuos values. Is it possible to tell all the code below

Thread.currentThread().setContextClassLoader( new URLClassLoader( urlsForModule1, ClassLoader.getSystemClassLoader().getParent() ) );

should use the above URLClassLoader to load the classes even if they are already loaded?

Apps
  • 3,284
  • 8
  • 48
  • 75
  • `even if they are already loaded`. If they are already loaded, why would you need to re-load them? Just load them with the correct `ClassLoader` from the start? Once a class is loaded the **only** way to un-load it is for the `ClassLoader` to be garbage-collected. Meaning if the classes were loaded by the System ClassLoader they will be loaded till the application terminates. – T-Fowl Oct 15 '14 at 06:44
  • I think you are looking for child-first classloaders (similar to web-app classloaders), by default the `URLClassLoader` uses parent-first. Try using the [ChildFirstURLClassLoader](http://stackoverflow.com/a/6424879/3080094) – vanOekel Oct 15 '14 at 07:25
  • These static files should have different data for the two modules which it gets from the class path set in the Class Loader So if it is the same Class loader, they will not be loaded again and will have the old value. – Apps Oct 15 '14 at 08:22

0 Answers0