GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [core] Refactor CPD internals to improve efficiency by oowekyala · Pull Request #6215 · pmd/pmd

Conversation

@oowekyala

@oowekyala oowekyala commented Nov 7, 2025

Copy link
Copy Markdown
Member

Describe the PR

This PR is work I undertook a while ago with the goal of reducing memory usage in CPD. The side effect is also improved runtime, in particular, lexing can be done in parallel now.

The main changes w.r.t. memory usage are

  • We don't use TokenEntry internally anymore, instead we use a data structure "TokenFile" that stores the token list in exploded arrays. This reduces memory usage because we don't create as many objects, and puts less frequently used data (like line/column information) out of the way.
    • Actual TokenEntry objects are only created on demand. As of now, this is only required during reporting and in infrequently used methods of the Tokenizer API.
    • Outside of those situations, whenever we want to refer to a token, we use the class "SmallTokenEntry", which is conceptually a pair of ints (file index, token index in file).
  • Since we create one TokenFile per source file (instead of using a global Tokens instance for all files), we can now lex source code in parallel in a bit the same way we run PMD in parallel. Although the hashing/matching phase is still sequential, this change is a large performance improvement as the runtime is dominated by the lexing phase in large projects.
  • I revised the MatchCollector to avoid work in some cases, you can see comments in there.
  • The hashing phase also pre-prunes pairs of tokens we know are going to be subsumed by a larger match. This is a great contributor to performance improvements for CPD from what I've seen.

The way I rewrote the algorithm allows for compacting several near-matches into one larger match. For this to happen all matches must have a common prefix longer than the minimum tokens parameter. This might report something like this:

Found a 24 line (130..147 tokens) duplication in the following files: 
Starting at line 907 of /home/.../resources/ext/TimeZoneNames_de.java
Starting at line 907 of /home/.../resources/ext/TimeZoneNames_es.java
Starting at line 907 of /home/.../resources/ext/TimeZoneNames_fr.java
...

This means that all of the duplicates have at least 130 tokens in common, and at least two of them have even 147 tokens in common. It prevents us from reporting different duplicates which look alike but only differ by a couple of tokens at their end, which is noisy. We would need an update to renderers like CSV and XML to report this properly.

Numbers

On my machine, running CPD on the JDK sources (14k files, 2.2MLOC):

  • main: 23-25s, peak memory > 9GB (crashes with less memory)
  • this branch: 8s (1 thread) or 6 seconds (8 threads), peak memory < 900MB
    Those numbers are without discounting warmup (so a lot of time is jvm startup), ran on an OpenJDK 21.0.8 runtime. Below I report some numbers for the same workload but with warmup time excluded.
Scaling case study (click to reveal) I benchmarked CPD more closely on those sources to see how it scales w.r.t threads and found the following. (The plots use warmup iterations so the numbers are better than above). Pasted image 20251029183939

The most obvious thing here is that adding threads improves performance until it starts degrading it. This is caused by contention on the shared map that records the integer ID of each token image.

I improved this by adding a read-only map that stores pre-allocated IDs for common tokens (keywords, punctuation, etc). The concurrent map is only queried if the image is not one of those known tokens. From what I saw, 2/3 of the tokens are punctuation or keywords, so this is very effective to reduce contention on the map. Here is a refreshed plot with this optimization.

Pasted image 20251029183838

Note that these plots are comparing a late version of this branch and the latest optimization I added, they're not a comparison to main. But, I thought the plots look cool, and CPD on main wouldn't fit on the plot!

Related issues

  • Fix [core] CPD throws java.lang.OutOfMemoryError: Java heap space #6145
  • Fix [cpp] PMD-7.4.0 CPD exception "java.lang.OutOfMemoryError: Java heap space" #5466

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
oowekyala added 30 commits May 2, 2024 15:08
@oowekyala
Optimize CPD for memory
7560a7b
Don't create TokenEntry instances unless needed for reporting.
Matching algorithm and internal state can use more compressed
representations with fewer indirections.
@oowekyala
Make CPD not fail on invalid unicode escapes
428d18f
@oowekyala
Update CPD to use TokenFileSet internally
477c209
@oowekyala
Dont use integer as key as that takes up heap space
63e8609
@oowekyala
Many optimizations
ccd14d7
@oowekyala
WIP parallelize CPD
73e3ea0
@oowekyala
Simplify, fix concurrency bug
593bff9
@oowekyala
Also make reportMatches more granular, lock on match
4039fed
@oowekyala
Use data structure properly
0f126df
@oowekyala
Todo cleanup
53b6727
@oowekyala
use treeset
c05d310
@oowekyala
Really report only maximal matches
9bb2db2
@oowekyala
Prune embedded duplicates early, during h construction
b931189
@oowekyala
Avoid collision on small hashes
766ecff
@oowekyala
Finish optimizing MatchCollector for speed
d41196f
We could do more for memory consumption though
@oowekyala
Fold several matches into one if they vary by a few tokens
a260e04
@oowekyala
Cleanups
4c9906b
@oowekyala
Encapsulate hashmap
f213b96
@oowekyala
Remove intHashMap
df983e0
Huge performance degradation
@oowekyala
Revert "Remove intHashMap"
551a1d1
This reverts commit 22a013b97b75f6f5c7e58fc323bb58932df67e67.
@oowekyala
Fix CPD test
307c57c
@oowekyala
Cleanups
a45095c
@oowekyala
Cleanup and fix tests
c9674cb
@oowekyala
Fix ordering of match of size 2
3c94ceb
@oowekyala
Cleanup, remove deprecated api
78ce65f
@oowekyala
Make CPD threads configurable
7373bb1
@oowekyala
Cleanups
a7ef700
@oowekyala
Better check prevtoken
59cbeb4
@oowekyala
move TokenHashMap out
597b85a
@oowekyala
Use FastUtil instead
c2c1298
@adangel adangel added this to the 7.20.0 milestone Nov 27, 2025
@adangel

adangel commented Nov 27, 2025

Copy link
Copy Markdown
Member

Thanks for this improvement. Unfortunately I won't have time to review it until the release tomorrow - and it seems to be a substantial change.
Before even looking at this, I want to have these metrics added to pmd regression tester - that means, first we need to improve the regression tester to also test CPD and also to monitor cpu time and memory. Because then, it would be much easier to see: "Aha, this PR causes PMD to use two more GB heap than before" (similar like: "This PR created 500 new violations").
So, I moved it to 7.20.0...

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

jsotuyod
jsotuyod reviewed Nov 27, 2025
View reviewed changes
Comment thread pmd-cpp/src/test/java/net/sourceforge/pmd/lang/cpp/cpd/CppCpdTest.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

@oowekyala

oowekyala commented Nov 28, 2025

Copy link
Copy Markdown
Member Author

Before even looking at this, I want to have these metrics added to pmd regression tester - that means, first we need to improve the regression tester to also test CPD and also to monitor cpu time and memory. Because then, it would be much easier to see: "Aha, this PR causes PMD to use two more GB heap than before" (similar like: "This PR created 500 new violations").

This is a good idea. TBH i wasn't able to collect heap size numbers in an automated way. If you have ideas about how to do that that would be great

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

oowekyala added 3 commits November 28, 2025 12:16
@oowekyala
Merge branch 'main' into cpd-opts
43432ef
@oowekyala
Merge branch 'main' into cpd-opts
58248d3
@oowekyala
Fix couple of tests abt cyclic repetition
1955f94
@adangel

adangel commented Nov 29, 2025

Copy link
Copy Markdown
Member

Before even looking at this, I want to have these metrics added to pmd regression tester - that means, first we need to improve the regression tester to also test CPD and also to monitor cpu time and memory. Because then, it would be much easier to see: "Aha, this PR causes PMD to use two more GB heap than before" (similar like: "This PR created 500 new violations").

This is a good idea. TBH i wasn't able to collect heap size numbers in an automated way. If you have ideas about how to do that that would be great

I was also looking into this the last few days/weeks. We could continue, what I did in main...adangel:pmd:core/cpd-memory-usage and manually measure the metrics (like peak heap usage). This can be extended to monitor also cpu usage (see https://github.com/kabutz/teardown-talk/blob/master/src/main/java/eu/javaspecialists/tjsn/talks/teardown/util/Benchmark.java for an example). You can even monitor allocations (https://github.com/kabutz/teardown-talk/blob/master/src/main/java/eu/javaspecialists/tjsn/talks/teardown/util/ByteWatcherSingleThread.java). This approach basically uses the MBeans to query the VM statistics.

But... there is JFR (JDK Flight Recorder) and this should bring us those numbers for free (and much more). JFR should be available since Java 11. As long as we run PMD with Java 11+ it should work. I played around with this now and I think, we should add it to the regression tester:

  1. Start PMD with PMD_JAVA_OPTS="-XX:StartFlightRecording:filename=recording.jfr,settings=custom.jfc,dumponexit=true". (I've created a simple custom settings file using jfr configure --interactive - we might need to tweak it)
  2. Analyze the recording on the CLI (we can do this on the ruby side a bit more comfortably, but just to see, how to get the basic numbers out of that, I did it with jq):
# start end end timestamps
jfr print --json --events jdk.JVMInformation,jdk.Shutdown recording.jfr |jq '.recording.events[0].values.jvmStartTime, .recording.events[1].values.startTime'
"2025-11-29T17:43:38.513+01:00"
"2025-11-29T17:50:50.947936009+01:00"

# duration in seconds
jfr print --json --events jdk.JVMInformation,jdk.Shutdown recording.jfr |jq '
   [ .recording.events[0].values.jvmStartTime, .recording.events[1].values.startTime
      | match("([0-9]+-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+).[0-9]+([+-][0-9]+:[0-9]+)")
      | .captures[0].string + .captures[1].string
      | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime
   ] | .[1] - .[0]'
432

jfr print --json --events jdk.JVMInformation,jdk.Shutdown recording.jfr |jq '
   [ .recording.events[0].values.jvmStartTime, .recording.events[1].values.startTime
      | match("([0-9]+-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+).[0-9]+([+-][0-9]+:[0-9]+)")
      | .captures[0].string + .captures[1].string
      | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime
    ] | (.[1] - .[0]) / 60 * 10 | floor / 10 | tostring + " minutes"'
"7.2 minutes"

# max heap memory
jfr print --json --events jdk.GCHeapSummary recording.jfr | jq '[.recording.events[].values.heapUsed]|max'
976278600

jfr print --json --events jdk.GCHeapSummary recording.jfr | jq '[.recording.events[].values.heapUsed]|max / 1024 / 1024 * 10 | floor / 10 | tostring + "GB"'
"931GB"

# max cpu load
jfr print --json --events jdk.CPULoad recording.jfr | jq '[.recording.events[].values.jvmUser]|max'
0.5767327

jfr print --json --events jdk.CPULoad recording.jfr | jq '[.recording.events[].values.jvmUser]|max * 1000 | floor / 10 | tostring + "%"'
"57.6%"

# average cpu load
jfr print --json --events jdk.CPULoad recording.jfr | jq 'add(.recording.events[].values.jvmUser) / (.recording.events | length)'
0.25153296741258757

jfr print --json --events jdk.CPULoad recording.jfr | jq '(add(.recording.events[].values.jvmUser) / (.recording.events | length) * 1000) | floor / 10 | tostring + "%"'
"25.1%"
  1. Include these basic numbers in the html report and baseline for comparison.

  2. We can include the recording.jfr into the regression report. You can then download it and open it with JDK Mission Control (https://adoptium.net/de/jmc) to have a deeper look.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced Nov 29, 2025
Add support for CPD regression testing pmd/pmd-regression-tester#145
Closed
Add support for measuring CPU and Memory usage pmd/pmd-regression-tester#146
Closed
@jsotuyod

jsotuyod commented Nov 29, 2025

Copy link
Copy Markdown
Member

+1 on using JFR. Low overhead, reliable, applicable to all PMD modes (CPD, PMD, etc.) and no maintenance on our end.

UncleOwen reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@adangel adangel modified the milestones: 7.20.0, 7.21.0 Dec 28, 2025
@adangel adangel modified the milestones: 7.21.0, 7.22.0 Jan 30, 2026
@adangel

adangel commented Feb 22, 2026

Copy link
Copy Markdown
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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@adangel adangel modified the milestones: 7.22.0, 7.23.0 Feb 22, 2026
@adangel adangel mentioned this pull request Mar 20, 2026
chore: bump pmd-regression-tester from 1.6.2 to 1.7.0 #6515
Merged
4 tasks
@adangel

adangel commented Mar 24, 2026

Copy link
Copy Markdown
Member

Moving this to 7.24.0. Depends on pmd/pmd-regression-tester#171 and new release of regression tester and #6515

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@adangel adangel modified the milestones: 7.23.0, 7.24.0 Mar 24, 2026
@adangel adangel modified the milestones: 7.24.0, 7.25.0 Apr 24, 2026
adangel added 2 commits April 30, 2026 09:11
@adangel
Merge branch 'main' into pr-6215
0ff382f
@adangel
Suppress CloseResource for ForkJoinPool
2b55c5b
We can't use try-with-resources here, as we compile against Java 8.
But we build with Java 21 (enforced) and PMD uses that version for
the auxclasspath.
See also pmd#6224
@adangel

adangel commented May 7, 2026

Copy link
Copy Markdown
Member

@oowekyala

Good news - the OOM error for alsa-firmware is fixed. We have now 487 new duplications.

But I'm puzzled with the duplications for the java projects, e.g. checkstyle: we have 175 duplications less and 332 duplications changed. Or in other words: Before this change, we detected 507 duplications in checkstyle, now we only have 332.

Looking at the xml reports directly, I can see:

  • for the files section, everything stayed the same: the totalNumberOfTokens per File is the same, so tokenizing wasn't changed. Good.
  • When comparing the first changed duplication (AbstractCheck.java/AbstractFileSetCheck.java), there are only changes in the "beginToken" and "endToken" attributes - which are not displayed by the regression tester, but apparently compared.
    • other attributes (duplication length in lines/tokens, file positions) are the same. Good.
    • beginToken/endToken are different:
--- base-abstractcheck.xml	2026-05-07 08:32:34.114667477 +0200
+++ patch-abstractcheck.xml	2026-05-07 08:32:59.678176449 +0200
@@ -1,16 +1,16 @@
    <duplication lines="20" tokens="96">
-      <file begintoken="37874"
+      <file begintoken="271"
             column="5"
             endcolumn="59"
             endline="231"
-            endtoken="37969"
+            endtoken="366"
             line="212"
             path="/home/runner/work/pmd/target/repositories/checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java"/>
-      <file begintoken="38646"
+      <file begintoken="434"
             column="5"
             endcolumn="59"
             endline="218"
-            endtoken="38741"
+            endtoken="529"
             line="200"
             path="/home/runner/work/pmd/target/repositories/checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java"/>
       <codefragment><![CDATA[    }
  • I assume, beginToken/endToken are more internal details - yet they are in the XML report for some reason. Ok, reason is: [core] CPD: Added begin and end token to XML reports #4095 and [core] CPD: Add total number of tokens to XML reports #4021 (comment)
    • In both base and patch they look consistent, meaning "endToken - beginToken + 1 == tokens" - they represent the length of the duplication measured in number of tokens
    • The actual number has changed, which is probably expected, as you changed the implemention
    • I guess, we should adjust the regression tester to ignore the beginToken/endToken attributes when comparing. But all other attributes are still important for comparison (line, column, lines, tokens).

I started to look into the duplications of IndentationCheckTest.java. Some are the same. But one example of a change is: previously, we matched a bigger chunk (94 tokens) + smaller chunks (85 tokens and 61 tokens). Now, we seem to match only the smaller chunk (61 tokens)?

  • It could be, that this is what we want? E.g. previously, it looks like we reported the same code chunk multiple times in multiple duplications (overlapping regions maybe?)
  • Concrete example: IndentationCheckTest.java @ line 348
    • base: https://pull-requests.pmd-code.org/pr-6215/2b55c5b0620a9985cf42f6b3b19daab34299567f/regression/checkstyle/base_cpd_report.html reported 3 occurrences
    • patch: https://pull-requests.pmd-code.org/pr-6215/2b55c5b0620a9985cf42f6b3b19daab34299567f/regression/checkstyle/patch_cpd_report.html reports only 1 occurrence

@oowekyala What's the best approach to move forward here?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@adangel adangel removed this from the 7.25.0 milestone May 22, 2026
@lukasgraef lukasgraef mentioned this pull request Aug 8, 2026
fix: Ignore begintoken/endtoken in regression tester report pmd/pmd-regression-tester#214
Open
@noor-ahmadi noor-ahmadi mentioned this pull request Oct 3, 2026
[java] Reset CPD constructor detection for each file #7138
Merged
3 of 4 tasks

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@jsotuyod jsotuyod jsotuyod left review comments
@adangel adangel Awaiting requested review from adangel

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

[core] CPD throws java.lang.OutOfMemoryError: Java heap space [cpp] PMD-7.4.0 CPD exception "java.lang.OutOfMemoryError: Java heap space"

Uh oh!

There was an error while loading. Please reload this page.

3 participants

@oowekyala @adangel @jsotuyod
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.