Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaving Classloader open after first use

I am creating a URLClassloader to load some jars. Each jar gets loaded correctly from a different classloader and each jar contains a class with a method run(). Now the body of this run() can create an anonymous inner class in it. However, because i created my URLClassloader in a try-with-resources block it gets autoclosed and at run time when it tries to load the anonymous inner class it throws a NoClassDefFoundError because the classloader is already closed.

Now my question is, what is the normal practice for these situations? is it ok to leave the classloader open so that when later it needs to load something else, it can? is there a way to reopen a closed classloader?
If I leave the classloader open, the compiler gives me warnings about potential resource leaks so I have a feeling this is like streams where you are not supposed to leave them open indefinitely. However because of the nature of classloaders, if it's not the same classloader that loads the anonymous class, it cannot be used in the outer class

here is the code where the classloader is created

public Player(File codePath) throws PlayerException {

   try (URLClassLoader loader = new URLClassLoader(new URL[] { codePath.toURI().toURL() })) {

   //load class from Jar where run() method creates anonymous class that comes in the jar too


   } catch (ClassCastException | IOException | ClassNotFoundException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException
| SecurityException exc) {
throw new PlayerException("Error loading player's code", exc);

}
like image 845
Hilikus Avatar asked Dec 19 '12 02:12

Hilikus


1 Answers

The life time of a class loader should be at least the life time of the instances of the classes loaded with it. As long as they and their classes are not eligible for garbage collection neither is their class loader. And should they need to load additional code or resources you need the class loader open.

So when you're done with a player, that's the time when you should close the class loader.

like image 165
Philippe Marschall Avatar answered Sep 20 '22 13:09

Philippe Marschall