Fix thread safety issues in Communicator, Session, and AsyncPromiseFulfillerDecorator
Problem
Several thread safety issues exist in ocpp-common that can cause data corruption
or resource exhaustion under concurrent load:
-
Communicator:
transactionQueueuses non-thread-safeArrayDeque, but is accessed concurrently bysendCall()and theRetryRunnerthread without synchronization.failedFlagis a plainbooleanwith no cross-thread visibility guarantee. -
AsyncPromiseFulfillerDecorator: Default executor is
Executors.newCachedThreadPool()which creates threads without bound. When many chargers send requests simultaneously, this can exhaust memory withOutOfMemoryError: unable to create new native thread. -
Session.onCall(): The
synchronizedkeyword serializes all incoming CALL messages per session, but all internal state is already thread-safe (ConcurrentHashMap, stateless Gson, immutableFeatureRepository). Additionally,pendingPromisesentries are never removed after completion, causing unbounded map growth.
Changes
- Replace
ArrayDequewithConcurrentLinkedDequeandbooleanwithAtomicBooleaninCommunicator - Replace unbounded
CachedThreadPoolwith boundedThreadPoolExecutorinAsyncPromiseFulfillerDecorator(core=CPUs, max=CPUs×2, queue=1000,CallerRunsPolicyfor natural backpressure). ExistingsetExecutor()API is preserved for custom configuration. - Remove unnecessary
synchronizedfromSession.onCall() - Add
whenCompletecallback to auto-removependingPromisesentries
Tests
Added 3 new test classes (10 tests total):
AsyncPromiseFulfillerDecoratorTest— async delegation, non-blocking, executor resilienceCommunicatorConcurrencyTest— concurrent sendCall, concurrent sendCall + reconnectSessionConcurrencyTest— concurrent onCall, pendingPromises cleanup, concurrent completion
Hi @neinhart, I haven't fully looked into all issues, but this one:
| Additionally, pendingPromises entries are never removed after completion, causing unbounded map growth.
does not seem correct to me. See Session#completePendingPromise() which removes pendingPromises when completing.
Hi @robert-s-ubi, thanks for the careful review and the correction — you're right that my wording in the PR description was inaccurate.
Let me trace through the code more precisely:
Normal success path — you're correct:
SimplePromiseFulfiller.fulfill()callseventHandler.handleRequest(request)and gets aConfirmation- It then calls
eventHandler.asyncCompleteRequest(messageId, conf)(SimplePromiseFulfiller.java:47) asyncCompleteRequestdelegates tosession.completePendingPromise()(Server.java:143)completePendingPromiseremoves the entry from the map. ✅
So in the successful path, entries are removed correctly as you pointed out.
Exception path — where I think there is still a leak:
In SimplePromiseFulfiller.fulfill() (lines 49-54), if eventHandler.handleRequest(request) throws an exception, the catch block calls promise.completeExceptionally(ex) directly on the promise, bypassing asyncCompleteRequest/completePendingPromise.
} catch (Exception ex) {
logger.warn(\"fulfillPromise() failed\", ex);
if (promise != null) {
promise.completeExceptionally(ex); // <-- bypasses completePendingPromise
}
}
In this case, whenComplete(ConfirmationHandler) fires and sends back the error response, but the entry in pendingPromises is never cleaned up. Each exception from a handler leaks one entry.
The promise.whenComplete((result, error) -> pendingPromises.remove(id)) callback I added is a no-op in the success path (the entry is already gone) but handles the exception path as well.
That said, I agree the PR description overstates the issue — it's an edge case in the exception path, not a general leak. Would you prefer:
- I keep the
whenCompletecleanup as defensive and update the PR description to accurately describe the exception-path scenario, or - I remove this specific change from the PR (since it's a minor edge case) and the PR focuses only on the clear thread-safety fixes (
ArrayDeque,AtomicBoolean,ThreadPoolExecutor,synchronizedremoval)?
Happy to go either way. Thanks again for taking the time to review!
That said, I agree the PR description overstates the issue — it's an edge case in the exception path, not a general leak. Would you prefer:
- I keep the
whenCompletecleanup as defensive and update the PR description to accurately describe the exception-path scenario, or- I remove this specific change from the PR (since it's a minor edge case) and the PR focuses only on the clear thread-safety fixes (
ArrayDeque,AtomicBoolean,ThreadPoolExecutor,synchronizedremoval)?
@neinhart I'd prefer option 2, and put the promise leak in a separate PR. Something similar was already fixed with the promises for outgoing requests in this commit: https://github.com/ChargeTimeEU/Java-OCA-OCPP/commit/32903d4accb4dbd1bc8713725e3b684949e7ec4f - and that change replaced the existing promise removals with a single whenComplete() removal. I'd like to solve this issue the same way, if possible.