All pastes #2051122 Raw Edit

H2 Classloader Test

public java v1 · immutable
#2051122 ·published 2011-04-27 07:36 UTC
rendered paste body
import java.lang.ref.WeakReference;import java.lang.reflect.Method;import java.net.URLClassLoader;import java.sql.Connection;import java.sql.DriverManager;public class H2Test {    public static void main(String[] args) throws Exception {        WeakReference<ClassLoader> ref = createClassLoader();        System.gc();        System.err.println("classloader: " + ref.get()); // Should be null    }    private static WeakReference<ClassLoader> createClassLoader() throws Exception {        ClassLoader cl = new TestClassLoader();        Class<?> h2ConnectionTestClass = Class.forName("H2Test", true, cl);        Method testMethod = h2ConnectionTestClass.getDeclaredMethod("test");        testMethod.setAccessible(true);        testMethod.invoke(null);        return new WeakReference<ClassLoader>(cl);    }    static void test() throws Exception {        Class.forName("org.h2.Driver");        Connection connection;        connection =            DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE");        connection.close();        connection = null;        DriverManager.deregisterDriver(DriverManager.getDriver("jdbc:h2:mem"));    }    private static class TestClassLoader extends URLClassLoader {        public TestClassLoader() {            super(((URLClassLoader)TestClassLoader.class.getClassLoader()).getURLs(), ClassLoader                .getSystemClassLoader());        }        // This allows delegation of H2 to the AppClassLoader        @Override        public synchronized Class<?> loadClass(String name, boolean resolve)            throws ClassNotFoundException {            if (!name.contains("H2Test") && !name.contains("org.h2")) {                return super.loadClass(name, resolve);            }            Class<?> c = findLoadedClass(name);            if (c == null) {                try {                    c = findClass(name);                } catch (SecurityException e) {                    return super.loadClass(name, resolve);                } catch (ClassNotFoundException e) {                    return super.loadClass(name, resolve);                }                if (resolve) {                    resolveClass(c);                }            }            return c;        }    }}