JNDI, Tomcat, and ClassLoaders

If you want to use JNDI within a servlet container than you need to be careful to use the corresponding class loader for your shared resource. So, ensure that you have only one copy of the class in your JVM and then when you want to bind or lookup the resource use the resource's classloader. For example,

public <T> void bind(String name, Class<T> valueClass, T value) throws NamingException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        Context c = new InitialContext();
        Thread.currentThread().setContextClassLoader(valueClass.getClassLoader());
        c.bind(name, value);
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
}

public <T> T lookup(String name, Class<T> valueClass) throws NamingException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        Context c = new InitialContext();
        Thread.currentThread().setContextClassLoader(valueClass.getClassLoader());
        return (T) c.lookup(name);
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
}
I am passing the valueClass to bind() so that an interface can be used if wanted.