SpotBugs concurrency: holder-idiom singleton + volatile flag#7631
Open
Vest wants to merge 1 commit into
Open
Conversation
Four SpotBugs concurrency findings: - AT_STALE_THREAD_WRITE_OF_PRIMITIVE @ AbstractReferenceManufacturer:69 — isResolved is set by one thread in resolveReferences() and read on the variable-binding hot path from other threads. Without a memory barrier the reader can keep seeing a cached false indefinitely, and worse, a reader that does see true could still see a half-populated active map. Marked the field volatile; the write-once / read-many access pattern doesn't need full synchronization. - LI_LAZY_INIT_STATIC + SING_SINGLETON_GETTER_NOT_SYNCHRONIZED @ PluginFunctionLibrary.getInstance — classic broken double-init pattern (if (instance == null) instance = new ...). Replaced with the Initialization-on-Demand Holder Idiom. JVM class-init guarantees at-most-once, lazy, thread-safe publication with no synchronized, no volatile, and no allocation overhead. instance + list also became effectively final and the field can now be final. - THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION @ PluginFunctionLibrary.loadPlugin — narrowed throws Exception to throws ReflectiveOperationException, which is what clazz.getDeclaredConstructor().newInstance() actually throws. Also replaced the deprecated clazz.newInstance() with the getDeclaredConstructor().newInstance() form; the impl signature can narrow vs the interface's Exception. Added PluginFunctionLibraryTest (7 tests) pinning the singleton identity, load/reject/ignore contract for loadPlugin, and the unmodifiable view of getFunctions(). The volatile fix is a memory-model property and is not testable from a single-threaded JUnit run; behavioural regression is covered transitively by the 2965 itest cases that load real data through AbstractReferenceManufacturer.resolveReferences(). Verified: scoped pcgen.cdom.* + plugin.lsttokens.* (12075 tests, 0 failures), itest (2965 tests, 0 failures), spotbugsMain (4 targeted findings cleared, 0 new findings introduced).
Contributor
Author
|
I want to use LazyConstant, when we switch to another Java or LTS. |
This was referenced Jun 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Four SpotBugs concurrency findings in two files — all real thread-safety concerns.
Fixes
AT_STALE_THREAD_WRITE_OF_PRIMITIVE—AbstractReferenceManufacturer.java:69isResolvedwas a plainboolean, set by the data-load thread inresolveReferences()and then read on the variable-binding hot paths (lines 693, 1253) from other threads. Two real failure modes:falseindefinitely on memory architectures with weak ordering.truecould still see a half-populatedactivemap — theisResolved = truewrite isn't ordered with respect to the prior map writes.Marked the field
volatile. The write-once / read-many access pattern doesn't need fullsynchronized;volatilegives both visibility and the happens-before edge that orders the prior writes toactivebefore any reader who seestrue.LI_LAZY_INIT_STATIC+SING_SINGLETON_GETTER_NOT_SYNCHRONIZED—PluginFunctionLibrary.getInstance()Classic broken double-init pattern:
Replaced with the Initialization-on-Demand Holder Idiom:
JVM class-init guarantees the
Holderis initialised exactly once, lazily on firstgetInstance()call, and publishes a happens-before edge forINSTANCE. Nosynchronized, novolatile, no allocation overhead. Theinstancestatic field is gone; thelistfield can now befinal.THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION—PluginFunctionLibrary.loadPluginNarrowed
throws Exceptiontothrows ReflectiveOperationException, which is whatclazz.getDeclaredConstructor().newInstance()actually throws (coversNoSuchMethodException,InstantiationException,IllegalAccessException,InvocationTargetException). Also replaced the deprecatedclazz.newInstance()withgetDeclaredConstructor().newInstance(). The impl signature can legally narrow the interface'sthrows Exception.Why not
Spring/LazyConstantfor the singleton?Discussed during planning:
PluginFunctionLibraryis aPluginLoader, not a facet — sits next toPrerequisiteTestFactory.getInstance(),PJEP.getJepPluginLoader(), etc., none of which are Spring beans. Plugin loaders register duringMain.bootstrapbefore most Spring consumers come up. Adopting Spring here would mean either flipping bootstrap order for one outlier, or doing a project-wide refactor of allPluginLoader.getInstance()singletons — out of scope for a SpotBugs fix.LazyConstant(JEP 526, preview in JDK 26) is the JDK's eventual answer but still preview, requires--enable-previewon every JVM in the toolchain, and the two advantages it brings over the holder idiom (JIT constant-folding, retry-on-init-failure) don't apply here —getInstance()is called twice in the codebase against a no-op constructor. The holder idiom is the idiomatic Java answer that's been in Effective Java since 1998 and is JVM-spec thread-safe without any preview flag.Tests
New
PluginFunctionLibraryTest(7 tests) pinning:getInstance()returns same ref).getPluginClasses()returns{ FormulaFunction.class }.loadPluginregisters aFormulaFunction.loadPluginsilently ignores non-FormulaFunctionclasses.loadPluginrejects duplicate names without throwing.loadPluginpropagatesReflectiveOperationExceptionon a class with no accessible no-arg constructor.getFunctions()returns an unmodifiable view.The
volatilefix is a memory-model property and is not testable from a single-threaded JUnit run — writing a stress test that's reliable enough for CI would be more work than the fix and would essentially be testing the JVM spec. Behavioural regression is covered transitively by 2965itestcases that load real data throughAbstractReferenceManufacturer.resolveReferences(). This is called out in the test class Javadoc.Verification
./gradlew compileJava→ BUILD SUCCESSFUL:test --tests "pcgen.cdom.*" --tests "plugin.lsttokens.*"→ 12075 tests, 0 failures./gradlew :itest→ 2965 tests, 0 failures./gradlew spotbugsMain→ 4 targeted findings cleared, 0 new findings introduced. Total dropped from 76 → 72.Scope note
Standalone — independent of the still-open #7627 (
mark-cdom-classes-final) and the merged #7624–#7628. Branched off latestorigin/master.