簡體   English   中英

Htmlunit 2.27中的內存泄漏

[英]Memory leak in Htmlunit 2.27

我正在使用htmlunit

<dependency>
    <groupId>net.sourceforge.htmlunit</groupId>
    <artifactId>htmlunit</artifactId>
    <version>2.27</version>
</dependency>

我有一個簡單的循環,每一秒打印一些來自響應的數據:

public static void main(String[] args) throws InterruptedException, IOException {

        WebClient webClient;

        webClient = new WebClient();

        webClient = new WebClient();
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        final History window = webClient.getWebWindows().get(0).getHistory();
        final Field f;
        try {
            f = window.getClass().getDeclaredField("ignoreNewPages_"); //NoSuchFieldException
            f.setAccessible(true);
            ((ThreadLocal<Boolean>) f.get(window)).set(Boolean.TRUE);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
            System.out.println(ex.getMessage());
        }

        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            System.out.println(i);
            HtmlPage page = webClient.getPage("https://stackoverflow.com");
            System.out.println(page.getHead().toString());

            Thread.sleep(1000);

            webClient.getCookieManager().clearCookies();
            webClient.getCache().clear();

            final List<WebWindow> windows = webClient.getWebWindows();

            for (final WebWindow wd : windows) {

                wd.getJobManager().removeAllJobs();

            }

            webClient.close();

        }
    }

當我運行程序時,內存在增長,為什么? 這是蟲子? 要不然是啥?

for (int i = 0; i < Integer.MAX_VALUE; i++) {
    System.out.println(i);
    HtmlPage page = webClient.getPage("https://stackoverflow.com");
    System.out.println(page.getHead().toString());

    Thread.sleep(1000);

    webClient.getCookieManager().clearCookies();
    webClient.getCache().clear();

    final List<WebWindow> windows = webClient.getWebWindows();

    for (final WebWindow wd : windows) {
        wd.getJobManager().removeAllJobs();
    }
}

根據上面的循環,它看起來你正在加載整個SOF主頁Integer.MAX_VALUE次。 當然,這會產生記憶含義。

有人檢查過這段代碼和jProfiler,似乎根本沒有真正的內存泄漏。

public static void main(String[] args) throws Exception {
    for (int i = 0; i < Integer.MAX_VALUE; i++) {
        try (WebClient webClient = new WebClient()) {
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setHistorySizeLimit(0);

            System.out.println(i);
            HtmlPage page = webClient.getPage("https://stackoverflow.com");
            System.out.println(page.getHead().toString());
        }

        Thread.sleep(1000);
    }
}

暫無
暫無

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

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