Search code examples
javaclassloader

How to uniquely identify the instance of a class loader in Java


I have a problem which looks like it is being caused because two instances of a classloader are being used at the same time. A scheduled task is always being run twice instead of once, even with settings to avoid concurrent usage.

How can I uniquely identify the Class loader instance for a given class instance at runtime? I know its fully qualified name would be a combination of classloader, package, and class name. I want to know if two individual instances of the same class loader are running concurrently.

I tried logging, using the following, but it gave me nothing useful in terms of what I was actually hoping to see (something equivalent to a unique thread id etc). yes, it does give the type of classloader and its parent name but this is insufficient to assist me with the issue.

final String classLoaderInfoCurrentThread = Thread.currentThread().getContextClassLoader().toString();
final String classLoaderInfoClass = getClass().getClassLoader().toString();
logger.debug("Class loader info current thread: " + classLoaderInfoClass);
logger.debug("Class loader info class: " + classLoaderInfoCurrentThread);

Results of above:

Class loader info class: WebappClassLoader

context:

delegate: false

repositories: /WEB-INF/classes/

----------> Parent Classloader: org.apache.catalina.loader.StandardClassLoader@68de123

Any ideas much appreciated.

UPDATE:

Thanks for quick feedback. Using the system hashcode was sufficient to confirm same classloader. The hash on StandardClassLoader was also useful in retrospect as helpfully pointed out in comments. I ran check on thread ids which are different.

Using Spring with Tomcat, and Quartz 1.8 scheduling framework.

By raising the logging on Spring / Quartz, I am able to identify that two different scheduler instances are being started up:

org.quartz.core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v1.8.6) 'scheduler' with instanceId '<compname>.local1375104695468'
org.quartz.core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v1.8.6) 'scheduler' with instanceId '<compname>.local1375104696411'

It appears there is a known issue with this:

Quartz job runs twice when deployed on tomcat 6/Ubuntu 10.04LTS


Solution

  • System.identityHashCode(getClass().getClassLoader());

    will return different values for different classloaders. You can use it as classloader ID and include it in logging info.