GeezerVison is showing github.com — [core] Refactor CPD internals to improve efficiency by oowekyala · Pull Request #6215 · pmd/pmd
Conversation
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).
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.
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
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.
Don't create TokenEntry instances unless needed for reporting.
Matching algorithm and internal state can use more compressed
representations with fewer indirections.
We could do more for memory consumption though
Huge performance degradation
This reverts commit 22a013b97b75f6f5c7e58fc323bb58932df67e67.
|
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...
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
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
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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:
- 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)
- 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%"
-
Include these basic numbers in the html report and baseline for comparison.
-
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.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This was referenced Nov 29, 2025
|
+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
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
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.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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
|
@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
@oowekyala What's the best approach to move forward here?
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This branch has not been deployed
No deployments
Reviewers
adangel
Awaiting requested review from adangel
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
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.
|