簡體   English   中英

JDK1.7 ClassLoader內存泄漏

[英]JDK1.7 ClassLoader Memory Leak

我有孩子優先的UrlClassLoader來動態加載jar文件。 然后我做一個反射來調用加載的jar文件中的方法。 一旦完成,我寧願卸載類加載器。 然后我嘗試做一些壓力測試代碼,以確保我的代碼順利運行。 基本上,我嘗試做的是在循環語句中加載和卸載jar。 這是我的代碼:

    for (int i = 0; i < 1000; i++) {
        //Just to show the progress
        System.out.println("LOAD NUMBER : " + i);

        ChildFirstURLClassLoader classLoader = null;
        try {
            File file = new File("C:\\library.jar");
            String classToLoad = "com.test.MyClass";
            URL jarUrl = new URL("file:" + file.getAbsolutePath());

            classLoader = new ChildFirstURLClassLoader(new URL[] {jarUrl}, null);
            Class<?> loadedClass = classLoader.loadClass(classToLoad);
            Method method = loadedClass.getDeclaredMethod("execute",
                    new Class[] {});

            ClassLoader currCl= Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(classLoader);
            method.invoke(null);
            Thread.currentThread().setContextClassLoader(currCl);

            method = null;
            loadedClass = null;
        } finally {
            if (classLoader != null) {
                classLoader.close();
                classLoader = null;
            }
        }
    }

當我在JDK1.6下運行此代碼時,沒有classLoader.close(); 聲明,該代碼運行完美。 但是當我轉向JDK1.7時,有時我會得到java.lang.OutOfMemoryError: PermGen space錯誤。 不幸的是,它以不一致的方式發生。

確認泄漏源自哪里的最簡單方法是使用分析器來監控內存使用情況。 試試JProfiler或VisualVM。 它將使您能夠精確定位泄漏的確切位置,並為您提供有關是否以及如何修復泄漏的線索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM