Skip to content

[core] CPD throws java.lang.OutOfMemoryError: Java heap space #6145

Open

Description

@bsmith-silv

Affects PMD Version:

Only tested on 7.16, 7.17. Bug does not exist on 6.26

Description:

CPD is throwing java.lang.OutOfMemoryError: Java heap space on several tested projects that work without issue on version 6.26 running with identical parameters. Occurs even when memory is set to 16GB.

Notably, on alsa-firmware 1.2.1, which only has 54 C files (~134k LoC), and AllegroOGG 1.0.3-39.fc43, which only has 96 C files (~60k LoC)

Also reproducible on some other codebases:
alpineemail 2.26
mysql-server 9.4.0
mongodb r8.2.1

Exception Stacktrace:

[TRACE] Tokenizing ./alsa/systems/alsa-1.2.1-7/code/alsa-firmware-1.2.1/ymfpci/fw_writer.c
[TRACE] Tokenizing ./alsa/systems/alsa-1.2.1-7/code/alsa-firmware-1.2.1/ymfpci/hwmcode.c
[DEBUG] Running match algorithm on 54 files...
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at java.base/java.util.HashMap.resize(HashMap.java:700)
        at java.base/java.util.HashMap.putVal(HashMap.java:659)
        at java.base/java.util.HashMap.put(HashMap.java:608)
        at java.base/java.util.HashSet.add(HashSet.java:220)
        at net.sourceforge.pmd.cpd.MatchCollector.registerTokenMatch(MatchCollector.java:119)
        at net.sourceforge.pmd.cpd.MatchCollector.lambda$reportMatch$2(MatchCollector.java:103)
        at net.sourceforge.pmd.cpd.MatchCollector$$Lambda$146/0x00000008400fc440.accept(Unknown Source)
        at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
        at net.sourceforge.pmd.cpd.MatchCollector.reportMatch(MatchCollector.java:103)
        at net.sourceforge.pmd.cpd.MatchCollector.collect(MatchCollector.java:57)
        at net.sourceforge.pmd.cpd.MatchAlgorithm.lambda$findMatches$1(MatchAlgorithm.java:57)
        at net.sourceforge.pmd.cpd.MatchAlgorithm$$Lambda$138/0x00000008400fec40.accept(Unknown Source)
        at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
        at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
        at java.base/java.util.HashMap$ValueSpliterator.forEachRemaining(HashMap.java:1693)
        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
        at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
        at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
        at net.sourceforge.pmd.cpd.MatchAlgorithm.findMatches(MatchAlgorithm.java:53)
        at net.sourceforge.pmd.cpd.CpdAnalysis.findMatches(CpdAnalysis.java:205)
        at net.sourceforge.pmd.cpd.CpdAnalysis.performAnalysis(CpdAnalysis.java:164)
        at net.sourceforge.pmd.cli.commands.internal.CpdCommand.doExecute(CpdCommand.java:136)
        at net.sourceforge.pmd.cli.commands.internal.CpdCommand.doExecute(CpdCommand.java:27)
        at net.sourceforge.pmd.cli.commands.internal.AbstractAnalysisPmdSubcommand$$Lambda$87/0x00000008400e4440.apply(Unknown Source)
        at net.sourceforge.pmd.cli.internal.PmdRootLogger.executeInLoggingContext(PmdRootLogger.java:55)
        at net.sourceforge.pmd.cli.commands.internal.AbstractAnalysisPmdSubcommand.execute(AbstractAnalysisPmdSubcommand.java:185)
        at net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand.call(AbstractPmdSubcommand.java:30)
        at net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand.call(AbstractPmdSubcommand.java:16)
        at picocli.CommandLine.executeUserObject(CommandLine.java:2031)


Steps to reproduce:

curl -OL https://github.com/pmd/pmd/releases/download/pmd_releases%2F7.17.0/pmd-dist-7.17.0-bin.zip
unzip pmd-dist-7.17.0-bin.zip
alias pmd="./pmd-bin-7.17.0/bin/pmd"

curl -OL  https://github.com/alsa-project/alsa-firmware/releases/download/v1.2.1/alsa-firmware-1.2.1.zip
unzip alsa-firmware-1.2.1.zip

export PMD_JAVA_OPTS="-Xmx16g"
pmd cpd --verbose --minimum-tokens 100 --no-fail-on-error --format xmlold --language cpp ./alsa-firmware-1.2.1 > alsa-1.2.1.xml 2> alsa-1.2.1-err.log

PMD 6.26, by contrast, can handle a minimum token threshold of 20 with no issue:

CLASS_PATH=$(find ./pmd-bin-6.26.0/lib -name '*.jar' | tr '\n' ':' | sed 's/:$//')
java -Xmx16g -cp "$CLASS_PATH" net.sourceforge.pmd.cpd.CPD  --minimum-tokens 20 --skip-lexical-errors --format xml --language cpp   --files ./alsa-firmware-1.2.1 > alsa-1.2.1.xml 2> alsa-1.2.1-err.log

Running PMD through: [CLI]

Additional Info
Running primarily on Ubuntu 22.04, although this behavior has been observed on Windows 11 as well

java --version
openjdk 24.0.2-internal 2025-07-15

Related older issues:

Activity

  1. added
    a:bug
    on Oct 17, 2025
  2. zbynek commented on Oct 18, 2025

    @zbynek
    Contributor
  3. jsotuyod commented on Oct 19, 2025

    @jsotuyod
    Member

    Actually, PMD 7.0.0 should "work" too.

    The issue however, is that any of those versions would also produce insane number of reports for those files, with very little actual value (see #2438).

    For instance, the mentioned file (https://github.com/alsa-project/alsa-firmware/blob/master/emu/emu0404_netlist.h) has a particularly nefarious scenario. It's a single array with 54908 literals, with massive amounts of repetitions (ie: the exact line 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, appears 3233 times – over a total of 6889 lines… and that's not even considering different offsets).

    In order to produce meaningful reports, that is, only maximal and non-overlapping areas being reported, CPD needs to store some additional data as it goes through matches. The amount of memory is "small" but escalates linearly with the number of potential matches found that needs disambiguation. Unfortunately, on these worst-case scenarios, that can escalate very quickly.

    There are 3 ways to improve on this, from worst to best:

    • You increase the --minimum-tokens which in turns reduces the number of matches… this however, has an impact on the results for all the code. Not really recommended.
    • You use --ignore-literal-sequences to have the lexer completely skip over all literal sequences (such as this one), getting rid of the issue, but maybe failing to detect other smaller literal sequences that shouldn't be duplicated. Probably the best alternative if you don't want to change the source code however.
    • You actively ignore these particular literals by preceding them with a /* CPD-OFF */ comment (and an optional /* CPD-ON */ at the end if there is more code in the file you want to analyze). See https://docs.pmd-code.org/latest/pmd_userdocs_cpd.html#suppression
  4. zbynek commented on Oct 19, 2025

    @zbynek
    Contributor

    @jsotuyod the 7.0.0 improvement introduces tokenMatchSets -- do I understand correctly that these are essentially equivalence classes and could be deduplicated?

    POC patch
    Index: pmd-core/src/main/java/net/sourceforge/pmd/cpd/MatchCollector.java
    IDEA additional info:
    Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
    <+>UTF-8
    ===================================================================
    diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/MatchCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/MatchCollector.java
    --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/MatchCollector.java	(revision 684cbcd05cfe06b076733ca455a05ba0a2e5f4d9)
    +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/MatchCollector.java	(date 1760879502110)
    @@ -68,7 +68,7 @@
              *  - BC
              * It should be reduced to a single match with 3 marks
              */
    -        if (tokenMatchSets.computeIfAbsent(mark1.getIndex(), (i) -> new HashSet<>()).contains(mark2.getIndex())) {
    +        if (tokenMatchSets.computeIfAbsent(mark1.getIndex(), this::wrapInSet).contains(mark2.getIndex())) {
                 return;
             }
     
    @@ -116,8 +116,19 @@
         }
     
         private void registerTokenMatch(TokenEntry mark1, TokenEntry mark2) {
    -        tokenMatchSets.computeIfAbsent(mark1.getIndex(), (i) -> new HashSet<>()).add(mark2.getIndex());
    -        tokenMatchSets.computeIfAbsent(mark2.getIndex(), (i) -> new HashSet<>()).add(mark1.getIndex());
    +        Set<Integer> first = tokenMatchSets.computeIfAbsent(mark1.getIndex(), this::wrapInSet);
    +        Set<Integer> second = tokenMatchSets.computeIfAbsent(mark2.getIndex(), this::wrapInSet);
    +        if (first != second) {
    +            first.addAll(second);
    +            second.forEach(index -> tokenMatchSets.put(index, first));
    +        }
         }
     
         List<Match> getMatches() {
    @@ -144,4 +155,10 @@
                     || token1.isEof()
                     || token2.isEof();
         }
    +
    +    private Set<Integer> wrapInSet(Integer val) {
    +        HashSet<Integer> set = new HashSet<>();
    +        set.add(val);
    +        return set;
    +    }
     }
    
    Does the patch make sense?
  5. lukasgraef commented on Oct 19, 2025

    @lukasgraef
    Member

    @jsotuyod the 7.0.0 improvement introduces tokenMatchSets -- do I understand correctly that these are essentially equivalence classes and could be deduplicated?
    POC patch

    Does the patch make sense?

    @zbynek

    How much memory does the deduplication roughly save?
    Could we combine that with the BitSet change from #6150 to save even more memory?

  6. jsotuyod commented on Oct 19, 2025

    @jsotuyod
    Member

    @zbynek yes, sort of. They are not exact matches, but "categories" from which we need to pick one match.

    @lukasgraef yes, I think that usage of Bitset is actually very interesting. Very good insight. If you move that into a pr rather than a draft I'm happy to take a look at it.

  7. lukasgraef commented on Oct 19, 2025

    @lukasgraef
    Member

    @lukasgraef yes, I think that usage of Bitset is actually very interesting. Very good insight. If you move that into a pr rather than a draft I'm happy to take a look at it.

    @jsotuyod I've moved the PR to ready.

  8. zbynek commented on Oct 19, 2025

    @zbynek
    Contributor

    We have to deal with two different scenarios:

    • the standard case, when the categories are small (same snippet appears just a few times)
    • the extreme case when one category gets huge

    While Bitsets compress the information for the huge category, they are probably not the best for the standard case since storing just 2 numbers 1 and 100,000 may allocate 800,000 bytes of memory with default JDK implementation.
    Deduplication should have negligible (positive) effect in the standard case and a massive one in the extreme case. I could verify that the OOM is gone, but I don't have more precise numbers yet.

  9. lukasgraef commented on Oct 19, 2025

    @lukasgraef
    Member

    We have to deal with two different scenarios:

    * the standard case, when the categories are small (same snippet appears just a few times)
    
    * the extreme case when one category gets huge
    

    While Bitsets compress the information for the huge category, they are probably not the best for the standard case since storing just 2 numbers 1 and 100,000 may allocate 800,000 bytes of memory with default JDK implementation. Deduplication should have negligible (positive) effect in the standard case and a massive one in the extreme case. I could verify that the OOM is gone, but I don't have more precise numbers yet.

    There's also the SparseBitSet library (https://github.com/brettwooldridge/SparseBitSet) which claims to be more memory efficient than java.util.BitSet. Maybe that would fit better for both scenarios?

  10. zbynek commented on Oct 19, 2025

    @zbynek
    Contributor

    but I don't have more precise numbers yet.

    So the total heap dump is ~290MB and the hash map is ~280MB out of that for the single file.

    Image

    SparseBitSet might improve that further.

  11. adangel commented on Oct 29, 2025

    @adangel
    Member

    Alright, I did some testing with the various suggestions. Here are the results:

    Version Explanation:

    Summary:

    • 7.17.0 with bitset:
      • slightly more memory is used, if there is no/not so many problematic tokens (case 1)
      • fixes the problem for a single file (case 2)
      • still can't analyze the whole alsa-firmware project (case 3)
    • 7.17.0 with dedup: less memory, but different results
      • looks more promising (uses less memory), whole alsa-firmware project can be analyzed (case 3)
      • doesn't find all duplicates
      • this solution uses much less memory with java 25 (than with java 8)
    • combination dedup+bitset: a bit more memory, but faster?
      • seems to be faster, but that needs to be repeated

    Next steps (for 7.19.0):

    • figure out, why "7.17.0 with dedup" finds less duplicates
      • we need to establish a baseline with several projects, that we agree on, which duplicates are the correct duplicates
    • more tests with other projects/languages
      • actually compare the duplicates to make sure, the same are found (and not just compare the numbers)
    • decide, whether to use bitset or not

    Next steps (longer term):

    • we need regression testing for CPD as well. Therefore we should add something like core/cpd-memory-usage
      and output the peak memory, timings (and maybe more stats) into the report or in an additional file
      • otherwise we will always have the problem, that we don't have measurements
      • we could even output this in general at the end of the process (like maven once did). But I would put this
        behind a CLI flag/ENV flag.
    • extend pmd-regression-tester maybe? Or create a separate project?
      • goal is to automate the regression tests
      • select a couple of projects to run regression tests and create a baseline
    • check, whether we can do something about xml format to not consume so much memory...

    Detailed Results: Peak Memory Usage

    Note:

    • Timings are from my laptop and I didn't repeat the runs. These are not average times!
    • Used the memory setting -Xms500m -Xmx4g. That means, I don't have results for case 1/3 because of OOM

    Case 1: all without problematic files

    EXCLUSIONS="--exclude alsa-firmware-1.2.1/emu/hana_netlist.h alsa-firmware-1.2.1/emu/emu0404_netlist.h alsa-firmware-1.2.1/emu/emu1010_notebook_netlist.h alsa-firmware-1.2.1/emu/audio_dock_netlist.h alsa-firmware-1.2.1/emu/micro_dock_netlist.h alsa-firmware-1.2.1/emu/emu1010b_netlist.h alsa-firmware-1.2.1/cs46xx/cs46xx_image.h alsa-firmware-1.2.1/ymfpci/hwmcode.c alsa-firmware-1.2.1/wavefront/yss225.c alsa-firmware-1.2.1/sb16/sb16_csp_codecs.h alsa-firmware-1.2.1/maestro3/maestro3.h alsa-firmware-1.2.1/cs46xx/cwc4630.h alsa-firmware-1.2.1/echoaudio/ASIC/3G_ASIC.c alsa-firmware-1.2.1/echoaudio/ASIC/Gina24ASIC.c alsa-firmware-1.2.1/echoaudio/ASIC/Gina24ASIC_361.c"
    FILES="alsa-firmware-1.2.1"
    

    -> 39 files, 900933 tokens

    1.8.0_472:

    • 7.17.0 w/o bitset: 200.99MiB (~4 seconds), 286 duplicates
    • 7.17.0 with bitset: 255.22MiB (~4 seconds), 286 duplicates
    • 7.17.0 with dedup: 200.78MiB (~3 seconds), 284 duplicates
    • 7.17.0 with dedup+bitset: 247.22MiB (~4 seconds), 284 duplicates
    • 7.0.0: 201.60MiB (~3 seconds), 406 duplicates
    • 6.55.0: 526.94MiB (~5 seconds), 407 duplicates

    25.0.1:

    • 7.17.0 w/o bitset: 299.26MiB (~4 seconds), 286 duplicates
    • 7.17.0 with bitset: 369.20MiB (~4 seconds), 286 duplicates
    • 7.17.0 with dedup: 239.24MiB (~3 seconds), 284 duplicates
    • 7.17.0 with dedup+bitset: 345.16MiB (~4 seconds), 284 duplicates
    • 7.0.0: 272.64MiB (~3 seconds), 406 duplicates
    • 6.55.0: 384.33MiB (~ 3 seconds), 407 duplicates

    Case 2: only one file

    EXCLUSIONS=""
    FILES="alsa-firmware-1.2.1/emu/emu0404_netlist.h"
    

    -> 109828 tokens

    1.8.0_472:

    • 7.17.0 w/o bitset: 🔴 OOM (> 4GiB)
    • 7.17.0 with bitset: 1.37GiB (~62 seconds), 535 duplicates
    • 7.17.0 with dedup: 1.34GiB (~20 seconds), 470 duplicates
    • 7.17.0 with dedup+bitset: 1.03GiB (~16 seconds), 470 duplicates
    • 7.0.0: 188.52MiB (~26 seconds), 6402 duplicates
    • 6.55.0: 197.90MiB (~64 seconds), 6402 duplicates

    25.0.1:

    • 7.17.0 w/o bitset: 🔴 OOM (> 4GiB)
    • 7.17.0 with bitset: 735.24MiB (~71 seconds), 535 duplicates
    • 7.17.0 with dedup: 540.41MiB (~20 seconds), 470 duplicates
    • 7.17.0 with dedup+bitset: 526.17MiB (~13 seconds), 470 duplicates
    • 7.0.0: 163.71MiB (~22 seconds), 6402 duplicates
    • 6.55.0: 133.63MiB (~52 seconds), 6402 duplicates

    Case 3: all files

    EXCLUSIONS=""
    FILES="alsa-firmware-1.2.1"
    

    -> 54 files, 2081189 tokens

    1.8.0_472:

    • 7.17.0 w/o bitset: 🔴 OOM (> 4GiB)
    • 7.17.0 with bitset: 🔴 OOM (> 4GiB)
    • 7.17.0 with dedup: 1.63GiB (~ 12 minutes), 3071 duplicates
    • 7.17.0 with dedup+bitset: 1.69GiB (~ 8 minutes), 3071 duplicates
    • 7.0.0: 1.75GiB (~ n/a), 34165 duplicates, 🔴 OOM (> 4GiB) during XML report generation...
    • 6.55.0: 2.23GiB (~ n/a), 34166 duplicates, 🔴 OOM (> 4GiB) during XML report generation...

    25.0.1:

    • 7.17.0 w/o bitset: 🔴 OOM (> 4GiB)
    • 7.17.0 with bitset: 🔴 OOM (> 4GiB)
    • 7.17.0 with dedup: 703.37MiB (~14 minutes), 3071 duplicates
    • 7.17.0 with dedup+bitset: 869.01MiB (~ 7 minutes), 3071 duplicates
    • 7.0.0: 1.43GiB (~ n/a), 34165 duplicates, 🔴 OOM (> 4GiB) during XML report generation...
    • 6.55.0: 1.86GiB (~ n/a), 34166 duplicates, 🔴 OOM (> 4GiB) during XML report generation...

    Script:

    Script
    #
    # get alsa-firmware
    #curl -o alsa-firmware-1.2.1.zip -L https://github.com/alsa-project/alsa-firmware/archive/refs/tags/v1.2.1.zip
    #unzip alsa-firmware-1.2.1.zip
    
    export PMD_JAVA_OPTS="-Xms500m -Xmx4g"
    
    # Case 1
    #EXCLUSIONS="--exclude alsa-firmware-1.2.1/emu/hana_netlist.h alsa-firmware-1.2.1/emu/emu0404_netlist.h alsa-firmware-1.2.1/emu/emu1010_notebook_netlist.h alsa-firmware-1.2.1/emu/audio_dock_netlist.h alsa-firmware-1.2.1/emu/micro_dock_netlist.h alsa-firmware-1.2.1/emu/emu1010b_netlist.h alsa-firmware-1.2.1/cs46xx/cs46xx_image.h alsa-firmware-1.2.1/ymfpci/hwmcode.c alsa-firmware-1.2.1/wavefront/yss225.c alsa-firmware-1.2.1/sb16/sb16_csp_codecs.h alsa-firmware-1.2.1/maestro3/maestro3.h alsa-firmware-1.2.1/cs46xx/cwc4630.h alsa-firmware-1.2.1/echoaudio/ASIC/3G_ASIC.c alsa-firmware-1.2.1/echoaudio/ASIC/Gina24ASIC.c alsa-firmware-1.2.1/echoaudio/ASIC/Gina24ASIC_361.c"
    #FILES="alsa-firmware-1.2.1"
    
    # Case 2
    #EXCLUSIONS=""
    #FILES="alsa-firmware-1.2.1/emu/emu0404_netlist.h"
    
    #Case 3: all files
    EXCLUSIONS=""
    FILES="alsa-firmware-1.2.1"
    
    # PMD 7+
    PMD_HOME=..../pmd-bin-7.17.0
    time $PMD_HOME/bin/pmd cpd --verbose --minimum-tokens 100 --format xml --language cpp --dir $FILES 2>&1 | tee alsa-1.2.1-err.log
    
    # PMD 6.55.0
    #PMD_HOME=..../pmd-bin-6.55.0
    #time $PMD_HOME/bin/run.sh cpd --verbose --minimum-tokens 100 --format xml --language cpp --dir $FILES 2>&1 | tee alsa-1.2.1-err.log
  12. added this to the 7.19.0 milestone on Oct 29, 2025
  13. oowekyala commented on Oct 29, 2025

    @oowekyala
    Member

    I have a branch cpd-opts which improves by a lot the efficiency of CPD both in terms of memory and run time. For instance running on the full JDK sources is possible with < 900MB memory in < 6 seconds, whereas on master (even with #6150) it takes about 10GB memory and a minute. I'm preparing a PR, will use your scripts to compare to main @adangel.

  14. added
    for:performance
    on Oct 29, 2025
  15. modified the milestones: 7.19.0, 7.20.0 on Nov 27, 2025
  16. modified the milestones: 7.20.0, 7.21.0 on Dec 28, 2025
  17. modified the milestones: 7.21.0, 7.22.0 on Jan 30, 2026
  18. adangel commented on Feb 22, 2026

    @adangel
    Member

    I'm moving this to 7.23.0. I'm still working on the pmd-regression-tester (see pmd/pmd-regression-tester#169 ), but that won't be finished for this Friday's release.

  19. modified the milestones: 7.22.0, 7.23.0 on Feb 22, 2026
  20. modified the milestones: 7.23.0, 7.24.0 on Mar 24, 2026
  21. modified the milestones: 7.24.0, 7.25.0 on Apr 24, 2026
  22. removed this from the 7.25.0 milestone on May 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:bugfor:performance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions