Skip to content

[java] Fix #6780: NonThreadSafeSingleton checkNonStaticMethods contradicting impl - #6864

Merged
adangel merged 12 commits into
pmd:mainfrom
dweep-js:fix/6780-nonthreadsafesingleton-checknonstaticmethods
Sep 6, 2026
Merged

adangel merged 12 commits into
pmd:mainfrom
dweep-js:fix/6780-nonthreadsafesingleton-checknonstaticmethods

Conversation

@dweep-js

@dweep-js dweep-js commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Describe the PR

The checkNonStaticMethods property description says "Check for non-static methods," implying that when set to true (the default), non-static methods are analyzed by the rule. The implementation did the opposite: non-static methods were skipped when checkNonStaticMethods=true, and only checked when it was set to false.

This meant the rule silently missed non-static singleton getter methods (e.g. public Singleton getInstance()) under default settings, which is a common real-world form of this anti-pattern.

Fix: inverted the condition in NonThreadSafeSingletonRule#visit(ASTMethodDeclaration, Object) so the property now behaves as documented — true checks non-static methods, false skips them.

Tests: added two regression cases to NonThreadSafeSingleton.xml — one confirming a non-static getInstance() is flagged with default properties, and one confirming it's not flagged when checkNonStaticMethods=false. All 11 pre-existing test cases still pass unchanged, since they all exercise static methods and never hit the changed branch.

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)

… its description (pmd#6780)

checkNonStaticMethods=true (the default) was silently skipping
non-static methods instead of checking them - the exact opposite
of the documented behavior. Inverted the condition so the flag
now matches its Javadoc, and added regression tests covering both
the default (checked) and checkNonStaticMethods=false (skipped)
cases.
@pmd-actions-helper

pmd-actions-helper Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Documentation Preview

Compared to main:
This changeset changes 0 violations,
introduces 11 new violations, 0 new errors and 0 new configuration errors,
removes 1 violations, 16 errors and 9 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-09-06 18:24:45+00:00 for 8d69d13)

@zbynek

zbynek commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

The the bug was introduced 20 years ago by migration to Java in 6007383#diff-2a607102b1fe9a683c3b7e498cf69a1087e5289883022e799608a29e8e16a307.

For any user who configured the rule since then to be more strict (setting checkNonstaticMethods=false) this will now silently ignore some violations, not sure if that's acceptable. Actually it's not clear to me why should non-static methods be less dangerous than static ones for this rule -- @pmd/maintainers would it make sense to instead deprecate the property and make it a no-op?

@UncleOwen

Copy link
Copy Markdown
Member

Going even further back, both properties are part of the rule since it was added in 3cc106a. Unfortunately, neither commit has a link to a bug tracker. I would really like to see the rationale why checkNonStaticMethods and checkNonStaticFields were included in the rule. If we're calling a non-static method, this can't be about a singleton anymore, can it?

In any case, I agree that inverting the meaning of a 20-year-old flag would be problematic.

@zbynek

zbynek commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

The checkNonStaticFields option decides whether we want to check singleton or lazy loading pattern in general. The rule name only covers the former, but otherwise I think the property distinguishes two valid usecases.

For checkNonStaticMethods the following two samples are equivalent:

class Invoice {

  static Databse db;

  public short money;

  public void save() {
    if (db == null) {db = Database.connect("cloud");}
    db.saveInvoice(money);
  }
}

and

class Invoice {

  static Databse db;

  public short money;

  private static void initDB() {
   if (db == null) {db= Database.connect("cloud");}
  }

  public void save() {
    initDB();
    db.saveInvoice(money);
  }
}

Whether the "singleton" classification is applicable to these two samples is debatable, but it fits both equally well.
I don't see a reason why would anyone want a violation reported for the second sample and not the first, so ignoring the property would be IMHO an improvement.

@adangel adangel changed the title [java] Fix NonThreadSafeSingleton checkNonStaticMethods contradicting… [java] Fix #6780: NonThreadSafeSingleton checkNonStaticMethods contradicting impl Jul 17, 2026
@UncleOwen

Copy link
Copy Markdown
Member

Thanks for the explanation. Makes sense. But I think we should try to keep both flags. Enabling them makes the rule stricter, but also increases the risk of false positives. We have no way to know which initializations need to be thread-safe. Just my gut feeling.

Alternative proposal: Rename the rule to something like NonThreadSafeLazyInitialization. Deprecate the old rule, but don't forward uses of the old name to the new one (only <rule ... deprecated="true"> without ref=...). That way we can fix the new rule and users of the old rule aren't immediately impacted.

In any case, we should do the following:

  • Improve the rule doc. Add something like what zbynek wrote above to the property description.
  • Update the reference to Effective Java. This seems to refer to Item 48 in the first edition, which is Item 78 in the current, third, edition. We should also note that Item 3 encourages using an enum to implement the singleton pattern, which avoids the concurrency issues.
  • Maybe override dysfunctionReason to enforce the dependency between the two properties?

@adangel

adangel commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

It seems, that these two properties of the rule are totally untested. No test case uses these properties. The only testcase, that exercises a non-static method is this:

<test-code>
<description>From defect 1573591</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class A {
public final static String FOO = "0";
private String bar;
public void bla() {
if (this.bar == null) {
this.bar = FOO;
}
}
}
]]></code>
</test-code>

The bug id "1573591" refers to sourceforge's bug id, before they migrated to the new system. You can still search by this number and you'll find https://sourceforge.net/p/pmd/bugs/584/
This bug report has nothing to do this static/non-static methods, but a NPE fix...

In summary, I think, we can argue that we are actually fixing a false negative of this rule (that it ignores by default non-static methods). I like the idea of deprecating these properties, to make this clear.
If we want, we could introduce a new property "ignoreNonStaticMethods", in case someone wants this, but maybe we should not do this unless actually someone wants it.

The rule checks for a lazy-intialization pattern (if x == null x = new X()) and IMHO the rule should simply report this whether the method is static or not.

would it make sense to instead deprecate the property and make it a no-op?

Yes, I'd do it.

The checkNonStaticFields option decides whether we want to check singleton or lazy loading pattern in general. The rule name only covers the former, but otherwise I think the property distinguishes two valid usecases.

I'd argue, that whether it is a singleton or a lazy loading pattern can't be decided by just looking at the code. If there is only one instance of this class (e.g. a Spring singleton bean), then what looks like lazy loading is at the same time a singleton pattern (very unnecessary, but still). Even the rule description seems to make some assumptions already ("Static singletons are usually not needed as only a single instance exists anyway" ???).

Maybe in a separate PR, we should also deprecate the "checkNonStaticFields" property and rename the rule to "NonThreadSafeInitialization"?

So, in summary I'd suggest for this PR:

Then for the future, maybe create an issue to rename the rule to "NonThreadSafeInitialization" (or similar) and improve it further.

@UncleOwen

Copy link
Copy Markdown
Member

If the two of you are fine with deprecating the property, feel free to ignore my gut feeling!

@zbynek

zbynek commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

feel free to ignore my gut feeling

Your gut feeling is correct, the proposed change may create false positives. Maybe the release notes should mention how to get the current behavior by setting the XPath suppression property for this rule. But since setting up XPath suppression is relatively easy, maybe there's no need to maintain the deprecated property (?).

@UncleOwen

Copy link
Copy Markdown
Member

I didn't mean to derail the discussion. How should we proceed from here?

  • Should we merge this as-is?
  • Should we postpone this to PMD 8? If the bug has indeed been present for 20 years, maybe fixing it can wait?

I'm fine either way, you guys decide.

@zbynek

zbynek commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

I think making the buggy property no-op and documenting how to restore old behavior with XPath suppression would improve things and would not require major version bump.

If you see need for bigger changes (like renaming the rule or removing/deprecating the non-buggy property), it would make sense to wait for v8.

@zbynek zbynek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dweep-js Please make sure the property is ignored and mark it as deprecated.

Updated the NonThreadSafeSingletonRule to remove the check for non-static methods as it is now always enforced. Added deprecation notice for the ignored property.

@dweep-js dweep-js left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zbynek I have deprecated it

@dweep-js
dweep-js requested a review from zbynek August 8, 2026 03:05
@adangel adangel added this to the 7.28.0 milestone Aug 31, 2026
@adangel
adangel merged commit e80f725 into pmd:main Sep 6, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[java] NonThreadSafeSingleton: False negative with property checkNonStaticMethods

4 participants