shreshthkharbanda opened a new pull request, #1781:
URL: https://github.com/apache/commons-lang/pull/1781
## What
`EventListenerSupport.addListener(listener, false)` performs a non-atomic
check-then-act on the shared listener list:
```java
if (allowDuplicate || !listeners.contains(listener)) {
listeners.add(listener);
}
```
Two threads registering the same listener concurrently can both pass the
`contains` check and both `add`, producing a duplicate registration even though
`allowDuplicate` is `false`. Since this class is explicitly designed for
multi-threaded use (the field Javadoc notes the list is "intentionally a
thread-safe copy-on-write-array"), the compound operation should be atomic too.
## Fix
`CopyOnWriteArrayList` provides the atomic form of exactly this operation,
so the change is minimal:
- narrow the private field's declared type from `List<L>` to
`CopyOnWriteArrayList<L>` (already the documented, intentional implementation;
`readObject` already assigns one), and
- use `addIfAbsent(listener)` when duplicates are disallowed.
Single-threaded behavior is unchanged and `testAddListenerNoDuplicates`
passes as before.
## Testing
- Added `testAddListenerNoDuplicatesConcurrent`: eight threads released by a
latch all register the same listener with `allowDuplicate = false`; exactly one
registration must result. Deterministic under the fix.
- `mvn test -Dtest=EventListenerSupportTest`: 13/13 pass; `mvn
checkstyle:check` passes.
- `src/changes/changes.xml` entry added under 3.21.0.
No JIRA issue filed for this one — happy to open one on LANG if preferred.
The race was flagged by a static-analysis tool I'm building (whole-program
check-then-act detection on shared collection state); this PR is the manual
verification and fix.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01BnA6jPsqhsGZ9idxJQi3ZG
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]