为什么这个 GC overhead limit exceed 会发生?

Why does this GC overhead limit exceed occur?

我正在读取和解析一个纯文本文件,逐行读取,将每一行分解成句子,将每个句子拆分成单词,并将它们按句子和按文档存储到列表中。

输入文件包含 500 万行,所以我将 ArrayList 的大小设置为 5005000。我在 IntelliJ 中的堆大小如下:

# custom IntelliJ IDEA VM options

-Xms128m
-Xmx8192m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow

我的笔记本电脑有 15G 内存。读取 4500000 行后(如 print 语句所示),它变得非常慢。几分钟后,我收到:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

每一行(解析为一个文档)都很短,所以我的15G内存应该绰绰有余。文本文件大小仅为 800MB。当我在 Windows 10 中查看我的性能监视器时,它显示仅使用了大约 55% 的内存,这表明它死机时仍有大量内存可用。

请注意,在下面的代码中,我使用 'sentence.toCharArray()',因为它不是英文,所以我在实现中基本上将每个字符视为一个单词。

只有 500 万行,为什么它死了?

        List<List<List<String>>> allWords = new ArrayList<>(5005000);
        System.out.println("Load text from file: ");
        try {
            BufferedReader br = Utils.fileReader(filePath);

            String line;
            int lineNo = 0;
            while ((line = br.readLine()) != null) {
                List<List<String>> wordsPerDoc = new ArrayList<>();
                for (String sentence : segment(line)) {
                    List<String> wordsPerSentence = new ArrayList<>();
                    for (Character c : sentence.toCharArray()) {
                        wordsPerClause.add(Character.toString(c));
                    }
                    wordsPerDoc.add(wordsPerSentence);
                }
                allWords.add(wordsPerDoc);
                lineNo++;
                if(lineNo % 500000 ==0) {
                    System.out.println(lineNo);
                }
            }
            System.out.println("Loaded text from file. ");

            br.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

public List<String> segment(final String line) {
        List<String> sentences = new ArrayList<>();
        StringTokenizer tokenizer = new StringTokenizer(line, OtherConstants.BASIC_TOKENIZATION_DELIMITER, true);
        while (tokenizer.hasMoreTokens()) {
            String word = tokenizer.nextToken();
                sentences.add(word);
        }
        return sentences;
    }

您正在为 IntelliJ 更改内存配置文件

要为您的应用更改它:转到右上角的 运行 菜单;找到你的主要 class;点击 "Edit Configurations";并将 "VM options" 设置为 -Xmx4g 以获得 4 GB 的应用程序堆。

https://www.jetbrains.com/help/idea/run-debug-configuration-application.html 用于文档