Skip to content

[java] NonThreadSafeSingleton: False negative with ternary conditional operator #6747

Closed

Description

@Chordrain

PMD Version: 7.24.0
Category: NonThreadSafeSingleton
Severity: Warning (Multithreading)

Summary

PMD's NonThreadSafeSingleton rule flags the unsafe lazy-initialization pattern if (field == null) field = new T(); in a non-synchronized method (a classic check-then-act race).

When the same logic is rewritten as a ternary assignment — field = field == null ? new T() : field; — the rule no longer fires (false negative), even though the rewrite is semantically identical and exposes the very same data race under concurrent access.

Reproducer

before — if-form (2 findings)

public class LazyInitBefore {
    private static Object foo;
    private static Object bar;

    public static Object getFoo() {
        if (foo == null)
            foo = new Object();          // flagged
        return foo;
    }

    public static Object getBar() {
        if (bar == null)
            bar = new Object();          // flagged
        return bar;
    }
}

after — ternary form (0 findings)

public class LazyInitAfter {
    private static Object foo;
    private static Object bar;

    public static Object getFoo() {
        foo = foo == null ? new Object() : foo;   // FALSE NEGATIVE
        return foo;
    }

    public static Object getBar() {
        bar = bar == null ? new Object() : bar;   // FALSE NEGATIVE
        return bar;
    }
}

Expected behavior

NonThreadSafeSingleton should report the same number of findings on BEFORE and AFTER. The ternary form field = field == null ? new T() : field; is semantically identical to if (field == null) field = new T(); and has the same data-race window when invoked concurrently.

Actual behavior

  • Two if-form lazy inits → 2 findings (correct).
  • Two ternary-form lazy inits → 0 findings.

The matcher only recognizes the if-statement shape of the lazy-init pattern and does not look through the equivalent conditional-assignment ternary.

Activity

  1. added
    a:false-negative
    on Jun 2, 2026
  2. changed the title [-][java] FN: `NonThreadSafeSingleton` misses ternary-form lazy initialization[/-] [+][java] NonThreadSafeSingleton: False negative with ternary conditional operator[/+] on Jun 2, 2026
  3. added this to the 7.27.0 milestone on Aug 10, 2026
  4. added a commit that references this issue on Aug 10, 2026
    ff15eb5
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:false-negative

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions