Question

I have a tricky question.

My java program is doing in a loop such things:

loop:

  1. read external file with compiled java class into byte[] array.

  2. create a new instance of my own classloader.

  3. setbytes from the readed file to this instance of classloader.

  4. using created classloader create a new instance of object of the class from external file.

  5. call any method of the created object.

And where the problem is.

  1. When I run this program in debug mode it behaves as I expect, so if external file changed classloader loads new version of class and executes new version (if file didn't change it loads old version also of course).

  2. But when I run this program NOT in a debug mode it always executes old version despite the fact that the readed file has changed.

Maybe someone with a deeper knowledge of classloading issues and JVM behaviours can explain me this behaviour.

Was it helpful?

Solution

Here's a simplified version of what happens:

  1. The JVM loads classes and other resources into the classpath exactly once (unless running in debug mode) from the directories or Jars specified in the CLASSPATH environment variable.
  2. To do this, it uses ClassLoaders
  3. Once a resource has been loaded by a ClassLoader instance, it remains in memory until the ClassLoader is garbage collected.

The debug mode is a special mode provided by the JVM, and the classloader works harder to give you the latest version of the resource.

OTHER TIPS

It is not possible to reload the same class with the same class loader

you can find a well written article about dynamic class re/loading here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top