开发者

Class unloading in java

When a classloader is garbage collected, are the classes loaded by it unloaded? When the JVM is running is verbose mode, all the loaded classes are o/p. Similarly will the JVM log when it unloads a class?

I wrote a custom class loader to test this, but could not see any verbose log for unloading of the classes.

CustomClassLoader loader = new CustomClassLoader(new URL[]{}, CustomClassLoader.class.getClassLoader());
    loader.addURL("D:\\workspace\\ClassLoaderTest\\implementation.jar");

    Class c = null;
    try {
        c = Class.forName("Horse",false,loader);
        if (c != null) {
            try {
                Animal animal = (Animal)c.newInstance();
                animal.eat();
            }
            catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    catch(Exception e) {
        e.printStackTrace();
    }
            c = null;
    loader = null;
    byte[] b = new byte[58*1024*1024];
    System.gc();
    ClassLoadingMXBean clBean = ManagementFactory.getClassLoadingMXBean();
    System.out.println("Number of classes cu开发者_如何学JAVArrently loaded " + clBean.getLoadedClassCount());
    System.out.println("Number of classes loaded totally " + clBean.getTotalLoadedClassCount());
    System.out.println("Number of classes unloaded " + clBean.getUnloadedClassCount());

Even the ClassLoadingMXBean gives number of unloaded classes as 0.

How can i know that a class is unloaded when the class loader is GCed?


A classloader won't be garbage collected while any classes created for it are "live" - partly because you could ask the class for its classloader.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜