From fa50bd4966ab5e898966f940103c74e573ecb7b9 Mon Sep 17 00:00:00 2001 From: Zixuan Liu Date: Tue, 19 Aug 2025 18:54:13 +0800 Subject: [PATCH] [fix][broker] Add double-check for non-durable cursor creation Signed-off-by: Zixuan Liu --- .../mledger/impl/ManagedLedgerImpl.java | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java index 4b630a6b362df..00a3387df3caa 100644 --- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java +++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java @@ -1154,6 +1154,17 @@ public ManagedCursor newNonDurableCursor(Position startPosition, String subscrip return newNonDurableCursor(startPosition, subscriptionName, InitialPosition.Latest, false); } + private ManagedCursor getCachedNonDurableCursor(String cursorName) { + ManagedCursor cachedCursor = cursors.get(cursorName); + if (cachedCursor != null) { + if (log.isDebugEnabled()) { + log.debug("[{}] Cursor was already created {}", name, cachedCursor); + } + return cachedCursor; + } + return null; + } + @Override public ManagedCursor newNonDurableCursor(Position startCursorPosition, String cursorName, InitialPosition initialPosition, boolean isReadCompacted) @@ -1162,18 +1173,20 @@ public ManagedCursor newNonDurableCursor(Position startCursorPosition, String cu checkManagedLedgerIsOpen(); checkFenced(); - ManagedCursor cachedCursor = cursors.get(cursorName); - if (cachedCursor != null) { - if (log.isDebugEnabled()) { - log.debug("[{}] Cursor was already created {}", name, cachedCursor); - } - return cachedCursor; + ManagedCursor cachedNonDurableCursor = getCachedNonDurableCursor(cursorName); + if (cachedNonDurableCursor != null) { + return cachedNonDurableCursor; } // The backlog of a non-durable cursor could be incorrect if the cursor is created before `internalTrimLedgers` // and added to the managed ledger after `internalTrimLedgers`. // For more details, see https://github.com/apache/pulsar/pull/23951. synchronized (this) { + cachedNonDurableCursor = getCachedNonDurableCursor(cursorName); + if (cachedNonDurableCursor != null) { + return cachedNonDurableCursor; + } + NonDurableCursorImpl cursor = new NonDurableCursorImpl(bookKeeper, this, cursorName, startCursorPosition, initialPosition, isReadCompacted); cursor.setActive();