This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 5593d91a1638 CAMEL-27584: camel-file - a stopping idempotent read lock 
runs its pending delayed releases at once (#30910)
5593d91a1638 is described below

commit 5593d91a163824e149808b6bbfe6e2b9d33dd96e
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 14:48:13 2026 +0530

    CAMEL-27584: camel-file - a stopping idempotent read lock runs its pending 
delayed releases at once (#30910)
    
    With readLock=idempotent or idempotent-changed, 
readLockIdempotentReleaseAsync=true
    and a readLockIdempotentReleaseDelay, the read lock releases a file on its 
own
    scheduled thread pool after the delay. On stop it shut that pool down with
    shutdownGraceful(pool, 30000): it waited up to 30 seconds, then 
shutdownNow()
    dropped the releases still waiting. With a delay over 30 seconds the key of 
a
    rolled back file stayed in the repository and the file was never picked up
    again (with a persistent or clustered repository, not even after a restart),
    and every stop with a release pending blocked for up to 30 seconds.
    
    The read lock now keeps the release tasks it scheduled and runs the ones 
still
    waiting at once when it stops, then shuts the pool down. A task runs only 
once,
    in the pool or at stop.
    
    Also, idempotent-changed and idempotent-rename record that they own the key
    right after the add, so the abort removes it when the changed or rename 
check,
    or the removal of the key after a failed check, throws.
    
    Review:
    - a delayed read lock release that the pool rejects is not kept until the 
stop
    - log the number of delayed read lock releases the stop actually ran
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../file/strategy/DelayedReadLockReleaseTasks.java | 132 ++++++++++++++
 ...dempotentChangedRepositoryReadLockStrategy.java |  16 +-
 ...IdempotentRenameRepositoryReadLockStrategy.java |   3 +
 .../FileIdempotentRepositoryReadLockStrategy.java  |  13 +-
 .../strategy/DelayedReadLockReleaseTasksTest.java  |  59 +++++++
 .../FileIdempotentReadLockReleaseOnStopTest.java   | 194 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  11 ++
 7 files changed, 422 insertions(+), 6 deletions(-)

diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/DelayedReadLockReleaseTasks.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/DelayedReadLockReleaseTasks.java
new file mode 100644
index 000000000000..056d0861cc3e
--- /dev/null
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/DelayedReadLockReleaseTasks.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.strategy;
+
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The read lock release tasks that an idempotent read lock strategy scheduled 
with readLockIdempotentReleaseAsync and
+ * readLockIdempotentReleaseDelay, and that have not run yet. When the 
strategy stops it runs them at once: shutting
+ * down the thread pool would drop them, and their keys would stay in the 
idempotent repository, so the files would
+ * never be picked up again.
+ */
+final class DelayedReadLockReleaseTasks {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(DelayedReadLockReleaseTasks.class);
+
+    private final Set<Task> pending = ConcurrentHashMap.newKeySet();
+
+    /**
+     * Schedules the release task to run after the delay. When the thread pool 
does not accept it, the exception is
+     * thrown and the task is not kept for the stop.
+     */
+    void schedule(ScheduledExecutorService executorService, Runnable release, 
long delay) {
+        Task task = new Task(release);
+        pending.add(task);
+        try {
+            task.future = executorService.schedule(task, delay, 
TimeUnit.MILLISECONDS);
+        } catch (RuntimeException e) {
+            // not scheduled (the queue of the pool is full, or a pool of your 
own rejects it): do not keep it, with its
+            // exchange, until the stop
+            pending.remove(task);
+            throw e;
+        }
+    }
+
+    /**
+     * Runs the release tasks that have not run yet in the calling thread. A 
task runs only once, here or in the thread
+     * pool.
+     *
+     * @return the number of releases this call ran (and that did not fail)
+     */
+    int runPending() {
+        if (pending.isEmpty()) {
+            return 0;
+        }
+        // counts the tasks released here: a task that the thread pool runs 
meanwhile is skipped, and is not counted
+        int released = 0;
+        for (Task task : pending) {
+            try {
+                if (task.runNow()) {
+                    released++;
+                }
+            } catch (Exception e) {
+                LOG.warn("Error during releasing exclusive read lock on stop. 
This exception is ignored.", e);
+            }
+        }
+        if (released > 0) {
+            LOG.info("Released {} idempotent read locks at once, before their 
readLockIdempotentReleaseDelay, as the"
+                     + " read lock is stopping",
+                    released);
+        }
+        return released;
+    }
+
+    private final class Task implements Runnable {
+
+        private final Runnable release;
+        private final AtomicBoolean started = new AtomicBoolean();
+        private volatile Future<?> future;
+
+        Task(Runnable release) {
+            this.release = release;
+        }
+
+        @Override
+        public void run() {
+            runOnce();
+        }
+
+        /**
+         * Runs the release, unless it has already run (or is running) in 
another thread.
+         *
+         * @return true when this call ran the release
+         */
+        private boolean runOnce() {
+            if (started.compareAndSet(false, true)) {
+                try {
+                    release.run();
+                } finally {
+                    pending.remove(this);
+                }
+                return true;
+            }
+            return false;
+        }
+
+        /**
+         * Runs the release in the calling thread, unless it has already run 
(or is running) in the thread pool.
+         *
+         * @return true when this call ran the release
+         */
+        boolean runNow() {
+            Future<?> f = future;
+            if (f != null) {
+                f.cancel(false);
+            }
+            return runOnce();
+        }
+    }
+}
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
index b99e03bbd2e1..cb620809438a 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
@@ -18,7 +18,6 @@ package org.apache.camel.component.file.strategy;
 
 import java.io.File;
 import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelContextAware;
@@ -62,6 +61,7 @@ public class FileIdempotentChangedRepositoryReadLockStrategy 
extends ServiceSupp
     private int readLockIdempotentReleaseAsyncPoolSize;
     private ScheduledExecutorService readLockIdempotentReleaseExecutorService;
     private boolean shutdownExecutorService;
+    private final DelayedReadLockReleaseTasks delayedReleaseTasks = new 
DelayedReadLockReleaseTasks();
 
     public FileIdempotentChangedRepositoryReadLockStrategy() {
         this.changed = new FileChangedExclusiveReadLockStrategy();
@@ -105,6 +105,9 @@ public class 
FileIdempotentChangedRepositoryReadLockStrategy extends ServiceSupp
         }
 
         if (answer) {
+            // the key is ours from now on: if the changed check or the remove 
below throws, the abort that follows
+            // removes it
+            exchange.setProperty(asReadLockKey(file, 
Exchange.FILE_LOCK_IDEMPOTENT_ACQUIRED), true);
             // if we acquired during idempotent then check changed also
             answer = changed.acquireExclusiveReadLock(operations, file, 
exchange);
             if (!answer) {
@@ -160,10 +163,11 @@ public class 
FileIdempotentChangedRepositoryReadLockStrategy extends ServiceSupp
     }
 
     private void delayOrScheduleLockRelease(Runnable r) throws 
InterruptedException {
-        if (readLockIdempotentReleaseDelay > 0 && 
readLockIdempotentReleaseExecutorService != null) {
+        ScheduledExecutorService executorService = 
readLockIdempotentReleaseExecutorService;
+        if (readLockIdempotentReleaseDelay > 0 && executorService != null) {
             LOG.debug("Scheduling read lock release task to run asynchronous 
delayed after {} millis",
                     readLockIdempotentReleaseDelay);
-            readLockIdempotentReleaseExecutorService.schedule(r, 
readLockIdempotentReleaseDelay, TimeUnit.MILLISECONDS);
+            delayedReleaseTasks.schedule(executorService, r, 
readLockIdempotentReleaseDelay);
         } else if (readLockIdempotentReleaseDelay > 0) {
             LOG.debug("Delaying read lock release task {} millis", 
readLockIdempotentReleaseDelay);
             Thread.sleep(readLockIdempotentReleaseDelay);
@@ -378,10 +382,16 @@ public class 
FileIdempotentChangedRepositoryReadLockStrategy extends ServiceSupp
 
     @Override
     protected void doStop() throws Exception {
+        // run the delayed release tasks that are still waiting now, instead 
of waiting for their delay: shutting the
+        // thread pool down would drop them, and their keys would stay in the 
idempotent repository, so the files
+        // would never be picked up again
+        delayedReleaseTasks.runPending();
         if (shutdownExecutorService && 
readLockIdempotentReleaseExecutorService != null) {
             
camelContext.getExecutorServiceManager().shutdownGraceful(readLockIdempotentReleaseExecutorService,
 30000);
             readLockIdempotentReleaseExecutorService = null;
         }
+        // and the ones scheduled while the thread pool was shutting down
+        delayedReleaseTasks.runPending();
     }
 
 }
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
index b22bb772ce0f..61bf85c2c370 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRenameRepositoryReadLockStrategy.java
@@ -97,6 +97,9 @@ public class FileIdempotentRenameRepositoryReadLockStrategy 
extends ServiceSuppo
         }
 
         if (answer) {
+            // the key is ours from now on: if the rename check or the remove 
below throws, the abort that follows
+            // removes it
+            exchange.setProperty(asReadLockKey(file, 
Exchange.FILE_LOCK_IDEMPOTENT_ACQUIRED), true);
             // if we acquired during idempotent then check rename also
             answer = rename.acquireExclusiveReadLock(operations, file, 
exchange);
             if (!answer) {
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
index c7169bc60cd4..5149ad51ae96 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentRepositoryReadLockStrategy.java
@@ -18,7 +18,6 @@ package org.apache.camel.component.file.strategy;
 
 import java.io.File;
 import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelContextAware;
@@ -60,6 +59,7 @@ public class FileIdempotentRepositoryReadLockStrategy extends 
ServiceSupport
     private int readLockIdempotentReleaseAsyncPoolSize;
     private ScheduledExecutorService readLockIdempotentReleaseExecutorService;
     private boolean shutdownExecutorService;
+    private final DelayedReadLockReleaseTasks delayedReleaseTasks = new 
DelayedReadLockReleaseTasks();
 
     @Override
     public void prepareOnStartup(GenericFileOperations<File> operations, 
GenericFileEndpoint<File> endpoint) throws Exception {
@@ -149,10 +149,11 @@ public class FileIdempotentRepositoryReadLockStrategy 
extends ServiceSupport
     }
 
     private void delayOrScheduleLockRelease(Runnable r) throws 
InterruptedException {
-        if (readLockIdempotentReleaseDelay > 0 && 
readLockIdempotentReleaseExecutorService != null) {
+        ScheduledExecutorService executorService = 
readLockIdempotentReleaseExecutorService;
+        if (readLockIdempotentReleaseDelay > 0 && executorService != null) {
             LOG.debug("Scheduling read lock release task to run asynchronous 
delayed after {} millis",
                     readLockIdempotentReleaseDelay);
-            readLockIdempotentReleaseExecutorService.schedule(r, 
readLockIdempotentReleaseDelay, TimeUnit.MILLISECONDS);
+            delayedReleaseTasks.schedule(executorService, r, 
readLockIdempotentReleaseDelay);
         } else if (readLockIdempotentReleaseDelay > 0) {
             LOG.debug("Delaying read lock release task {} millis", 
readLockIdempotentReleaseDelay);
             Thread.sleep(readLockIdempotentReleaseDelay);
@@ -339,10 +340,16 @@ public class FileIdempotentRepositoryReadLockStrategy 
extends ServiceSupport
 
     @Override
     protected void doStop() throws Exception {
+        // run the delayed release tasks that are still waiting now, instead 
of waiting for their delay: shutting the
+        // thread pool down would drop them, and their keys would stay in the 
idempotent repository, so the files
+        // would never be picked up again
+        delayedReleaseTasks.runPending();
         if (shutdownExecutorService && 
readLockIdempotentReleaseExecutorService != null) {
             
camelContext.getExecutorServiceManager().shutdownGraceful(readLockIdempotentReleaseExecutorService,
 30000);
             readLockIdempotentReleaseExecutorService = null;
         }
+        // and the ones scheduled while the thread pool was shutting down
+        delayedReleaseTasks.runPending();
     }
 
 }
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/DelayedReadLockReleaseTasksTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/DelayedReadLockReleaseTasksTest.java
new file mode 100644
index 000000000000..42c8dbcbd7c3
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/DelayedReadLockReleaseTasksTest.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.strategy;
+
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * A delayed release that the thread pool rejects is not kept until the stop 
of the read lock.
+ */
+class DelayedReadLockReleaseTasksTest {
+
+    @Test
+    void rejectedReleaseIsNotKeptForTheStop() {
+        ScheduledThreadPoolExecutor accepting = new 
ScheduledThreadPoolExecutor(1);
+        // a shut down pool rejects with the default abort policy, as a pool 
with a full queue does
+        ScheduledThreadPoolExecutor rejecting = new 
ScheduledThreadPoolExecutor(1);
+        rejecting.shutdown();
+        try {
+            DelayedReadLockReleaseTasks tasks = new 
DelayedReadLockReleaseTasks();
+            AtomicInteger scheduled = new AtomicInteger();
+            AtomicInteger rejected = new AtomicInteger();
+
+            tasks.schedule(accepting, scheduled::incrementAndGet, 60000);
+            assertThrows(RejectedExecutionException.class,
+                    () -> tasks.schedule(rejecting, rejected::incrementAndGet, 
60000));
+
+            // the stop runs the pending release that was scheduled, and not 
the one that was rejected
+            assertEquals(1, tasks.runPending(), "The stop did not count the 
one release it ran");
+            assertEquals(1, scheduled.get(), "The scheduled release did not 
run at the stop");
+            assertEquals(0, rejected.get(), "The rejected release was kept and 
ran at the stop");
+            // a release runs once: nothing is left for a second stop
+            assertEquals(0, tasks.runPending(), "A release ran or was counted 
twice");
+            assertEquals(1, scheduled.get(), "The scheduled release ran 
twice");
+        } finally {
+            accepting.shutdownNow();
+        }
+    }
+}
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/FileIdempotentReadLockReleaseOnStopTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/FileIdempotentReadLockReleaseOnStopTest.java
new file mode 100644
index 000000000000..c3c9b75102d7
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/component/file/strategy/FileIdempotentReadLockReleaseOnStopTest.java
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.strategy;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * The idempotent read locks run their pending delayed release tasks when they 
stop, instead of waiting for the delay or
+ * dropping the tasks when the thread pool is shut down.
+ */
+class FileIdempotentReadLockReleaseOnStopTest extends ContextTestSupport {
+
+    // far longer than the 30 seconds the read lock waits for its thread pool 
when it stops
+    private static final int LONG_DELAY = 120000;
+
+    private final CountingRepository repo = new CountingRepository();
+    // the route fails the first file it routes
+    private final AtomicBoolean failFirst = new AtomicBoolean();
+    private final AtomicInteger routed = new AtomicInteger();
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "idempotent", "idempotent-changed" })
+    void testRollbackReleaseRunsWhenTheRouteStops(String readLock) throws 
Exception {
+        Path file = testFile("hello.txt");
+        Files.writeString(file, "Hello World");
+        failFirst.set(true);
+        startRoute("readLock=" + readLock + 
"&readLockCheckInterval=100&readLockIdempotentReleaseAsync=true"
+                   + "&readLockIdempotentReleaseDelay=" + LONG_DELAY);
+
+        // the route fails, and the removal of the key is scheduled after the 
delay
+        await().atMost(10, TimeUnit.SECONDS).until(() -> routed.get() >= 1);
+        assertThat(routed.get()).isEqualTo(1);
+        assertThat(repo.keys).hasSize(1);
+
+        // the stop runs the removal at once
+        CompletableFuture<Void> stop = stopRouteAsync();
+        await().atMost(10, TimeUnit.SECONDS).until(stop::isDone);
+        assertThat(stop).isCompleted();
+        assertThat(repo.keys).isEmpty();
+        assertThat(repo.removed.get()).isEqualTo(1);
+
+        // so the file is retried after a restart
+        context.getRouteController().startRoute("foo");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> !Files.exists(file));
+        assertThat(routed.get()).isEqualTo(2);
+    }
+
+    @Test
+    void testCommitReleaseRunsWhenTheRouteStops() throws Exception {
+        Path file = testFile("hello.txt");
+        Files.writeString(file, "Hello World");
+        
startRoute("readLock=idempotent&readLockRemoveOnCommit=true&readLockIdempotentReleaseAsync=true"
+                   + "&readLockIdempotentReleaseDelay=" + LONG_DELAY);
+
+        // the file is processed and deleted, the removal of the key is 
scheduled after the delay
+        await().atMost(10, TimeUnit.SECONDS).until(() -> routed.get() == 1 && 
!Files.exists(file));
+        assertThat(repo.keys).hasSize(1);
+
+        CompletableFuture<Void> stop = stopRouteAsync();
+        await().atMost(10, TimeUnit.SECONDS).until(stop::isDone);
+        assertThat(stop).isCompleted();
+        assertThat(repo.keys).isEmpty();
+
+        // a new file with the same name is processed after a restart
+        context.getRouteController().startRoute("foo");
+        Files.writeString(file, "Bye World");
+        await().atMost(10, TimeUnit.SECONDS).until(() -> routed.get() == 2 && 
!Files.exists(file));
+    }
+
+    @Test
+    void testReleaseThatRanIsNotRunAgainWhenTheRouteStops() throws Exception {
+        Path file = testFile("hello.txt");
+        Files.writeString(file, "Hello World");
+        failFirst.set(true);
+        
startRoute("readLock=idempotent&readLockIdempotentReleaseAsync=true&readLockIdempotentReleaseDelay=100");
+
+        // the route fails, the thread pool removes the key after the delay, 
and the file is processed again
+        await().atMost(10, TimeUnit.SECONDS).until(() -> routed.get() == 2 && 
!Files.exists(file));
+
+        context.getRouteController().stopRoute("foo");
+        assertThat(repo.removed.get()).isEqualTo(1);
+        assertThat(routed.get()).isEqualTo(2);
+    }
+
+    @Test
+    void testChangedKeyIsRemovedWhenTheCleanupAfterTheChangedCheckFails() 
throws Exception {
+        // shorter than readLockMinLength: the changed check fails after the 
key is added, and its cleanup fails once
+        Path file = testFile("hello.txt");
+        Files.writeString(file, "Hello");
+        repo.failRemove.set(true);
+        
startRoute("readLock=idempotent-changed&readLockMinLength=100&readLockTimeout=400&readLockCheckInterval=100");
+
+        // the abort that follows removes the key
+        await().atMost(10, TimeUnit.SECONDS).until(() -> repo.removed.get() >= 
1);
+
+        // so the file is processed once it is ready
+        Files.writeString(file, "x".repeat(200), StandardOpenOption.APPEND);
+        await().atMost(10, TimeUnit.SECONDS).until(() -> routed.get() == 1 && 
!Files.exists(file));
+    }
+
+    private void startRoute(String options) throws Exception {
+        context.getRegistry().bind("myRepo", repo);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from(fileUri("?initialDelay=0&delay=10&delete=true&idempotentRepository=#myRepo&"
 + options))
+                        .routeId("foo")
+                        .process(exchange -> {
+                            if (routed.incrementAndGet() == 1 && 
failFirst.get()) {
+                                throw new IllegalStateException("Forced");
+                            }
+                        })
+                        .to("mock:result");
+            }
+        });
+        context.start();
+    }
+
+    private CompletableFuture<Void> stopRouteAsync() {
+        return CompletableFuture.runAsync(() -> {
+            try {
+                context.getRouteController().stopRoute("foo");
+            } catch (Exception e) {
+                throw new IllegalStateException(e);
+            }
+        });
+    }
+
+    /**
+     * Keeps the keys it holds, counts the removals that succeed, and can fail 
one removal.
+     */
+    private static final class CountingRepository extends 
KeyValueIdempotentRepository {
+        private final Set<String> keys = ConcurrentHashMap.newKeySet();
+        private final AtomicInteger removed = new AtomicInteger();
+        private final AtomicBoolean failRemove = new AtomicBoolean();
+
+        @Override
+        public boolean add(String key) {
+            boolean answer = super.add(key);
+            if (answer) {
+                keys.add(key);
+            }
+            return answer;
+        }
+
+        @Override
+        public boolean remove(String key) {
+            if (failRemove.compareAndSet(true, false)) {
+                throw new IllegalStateException("Forced remove failure");
+            }
+            boolean answer = super.remove(key);
+            keys.remove(key);
+            removed.incrementAndGet();
+            return answer;
+        }
+    }
+}
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 4d6f339655cd..f8768d8fd505 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -1562,6 +1562,17 @@ file consumer no longer adds the key to the idempotent 
repository eagerly, and `
 read lock adds it when it acquires the lock. Since Camel 4.7 the read lock was 
refused, and such a consumer never
 consumed a file.
 
+=== camel-file - a stopping idempotent read lock releases its delayed read 
locks at once
+
+With `readLock=idempotent` or `idempotent-changed` and 
`readLockIdempotentReleaseAsync=true`, the read locks whose
+release still waits for `readLockIdempotentReleaseDelay` are released when the 
consumer stops, at once. Before, with the
+pool Camel creates, the stop waited for them for up to 30 seconds, and a 
release still pending after that was dropped:
+its key stayed in the idempotent repository, so the file was never picked up 
again (with a persistent or clustered
+repository, not even after a restart). With `readLockRemoveOnCommit=true`, the 
keys of the files a stopping node
+committed in the last `readLockIdempotentReleaseDelay` millis are now removed 
before the delay is over.
+This also applies with a `readLockIdempotentReleaseExecutorService` of your 
own, which Camel does not shut down:
+there, nothing was dropped before, and the pending releases now run at the 
stop instead of when their delay is over.
+
 === camel-spring-rabbitmq - the consumer starts while RabbitMQ is down, and 
declares again on a new connection
 
 With `autoDeclare=true` (the default), a consumer now starts when RabbitMQ is 
not available: the route shows as started,

Reply via email to