GeezerVison is showing github.com — [java] Fix #5016: UnusedAssignment: field may be read by a method call by Pankraz76 · Pull Request #7235 · pmd/pmd
Conversation
Pankraz76
commented
Oct 24, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
Describe the PR
UnusedAssignment reports a field write as unused when the same method overwrites it later, even when a method call in between can read the field. The typical case is a reentrancy guard (from #5016):
public void run(final Runnable runnable) {
if (entered) return;
try {
entered = true; // reported: "never used (overwritten on line 8)"
runnable.run(); // may call run() again, which reads `entered`
} finally {
entered = false;
}
}
The same false positive happens with static fields in static methods, even when the method calls the class's own static helper and that helper reads the field.
Root cause
DataflowPass.ReachingDefsVisitor#visit(ASTMethodCall) only treats a call as reading fields if it is a call on this:
if (trackThisInstance() && JavaAstUtils.isCallOnThisInstance(node) != OptionalBool.NO) {
state.recordThisLeak(enclosingClassScope, node);
}
That approach was built for constructors and initializers, where no other code can reach this yet (see the Javadoc of recordThisLeak). PMD 7 started tracking fields inside methods too and reused the same approach. But inside a method, the caller already holds a reference to this, and static fields can be reached from anywhere, so any method call may read them. That explains why the reporter saw this as a regression from PMD 6.
The fix
- The visitor now knows whether it is processing a method body (
inMethod).
- Inside a method body, every method call counts as possibly reading all the class's fields that the pass tracks (only static fields in a static method). This reuses the existing
UNKNOWN_METHOD_CALL mechanism.
- This is recorded after the call's receiver and arguments are evaluated, which is the order Java evaluates them in (JLS §15.12.4). A test in
LawOfDemeter.xml covers this order.
- Constructors and initializers are unchanged, so they keep the existing precise tracking of when
this leaks.
- Constructor calls (
new X()) deliberately don't count as reading fields. They rarely call back into existing objects, and counting them would hide real copy-paste mistakes like f = new X(); f = new X();.
Tests
UnusedAssignment.xml:
LawOfDemeter.xml: checks that a call's receiver is read before the call can change fields.
- On
main, only the two new tests that expect no violation fail. All 589 tests of the 10 rules that use DataflowPass pass with the fix.
./mvnw -pl pmd-java verify passes: 10,482 tests with 0 failures, plus Checkstyle, the PMD/CPD self-checks and japicmp.
- I compared results before and after the change on real projects, running all 10 rules that use
DataflowPass. No new violations appeared; only UnusedAssignment reports were removed:
- commons-lang: no change.
- commons-collections: one report removed,
AbstractPatriciaTrie:639. It was a real dead store, but the code in between iterates a view backed by this, so analysing one method at a time can't show it is safe.
- spring-framework, measured with an earlier draft that already handled method calls in this order: five reports removed.
ConfigurationClassParser:827 was a real false positive: processGroupImports() calls back into handle(), which checks deferredImportSelectors == null.
MBeanClientInterceptor:267 and the two SubscriberInputStream reports (on a volatile field) are writes that other code can see.
GenericConversionServiceBenchmark:96 was a real dead store and is no longer reported.
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.
…hod call
DataflowPass only considered calls on `this` as observing fields. That model
was designed for ctors, where `this` has not leaked yet. In a method, the class
and `this` are already reachable by other code, so any method call may observe
their fields, eg a callback reentering the object. Record that after the receiver
and arguments are evaluated. Ctors and initializers are unchanged.
Fixes pmd#5016
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DF77nmh5VDJQkunNQTikfo
Pankraz76
changed the title
[java] Fix #5016: UnusedAssignment: field may be observed by a method call
[java] Fix #5016: UnusedAssignment: field may be read by a method call
Oct 24, 2026
About how broad this is
After this change, every method call inside a method body counts as a possible read of every field in the class. So the rule no longer flags an overwrite like x = 1; log.debug("..."); x = 2; in a method. That's on purpose:
- Why any call: once a method is running,
this and the class can already be reached by other code. Any call (a callback, a listener, or anything going through a parameter, a field or a static) can come back into the object and read the field. We can't tell which calls do that without analysing the whole program, so the only safe default is to assume any call might.
- Constructors and initializers are unchanged:
this hasn't escaped there yet, so the existing check, which only looks at calls on this, still applies.
new X() is not counted: this keeps the change small. Constructor calls that receive this could be added later if wanted.
- Checked on real projects: I compared results on commons-lang, commons-collections and spring-framework. There were no new violations, and the reports that disappeared were false positives or harmless. One was a real false positive in spring-framework's
ConfigurationClassParser.
If you'd prefer a narrower approach, one option is to skip calls that clearly can't come back into the object, such as known library methods like a logger or System.out. I'm happy to do that here or in a follow-up.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Documentation Preview
Compared to main:
This changeset changes 0 violations,
introduces 0 new violations, 0 new errors and 0 new configuration errors,
removes 38 violations, 0 errors and 0 configuration errors.
There are 0 changed duplications, 0 new duplications and 0 removed duplications.
There are 0 changed CPD errors, 0 new CPD errors and 0 removed CPD errors.
Regression Tester Report
(comment created at 2026-11-20 14:33:24+00:00 for ded0fed)
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
adangel
changed the title
[java] Fix #5016: UnusedAssignment: field may be read by a method call
[java] Fix #5016: UnusedAssignment: field may be read by a method call
Nov 20, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
Reviewers
adangel
adangel approved these changes
Uh oh!
There was an error while loading. Please reload this page.
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.
|