You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ozone.apache.org by si...@apache.org on 2026/10/22 18:50:17 UTC

(ozone) branch master updated: HDDS-16164. DirectoryDeletingService could deadlock snapshot purge while retaining snapshot DB handles (#11009)

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

smengcl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new bf3829e6c8a HDDS-16164. DirectoryDeletingService could deadlock snapshot purge while retaining snapshot DB handles (#11009)
bf3829e6c8a is described below

commit bf3829e6c8ac69ae17585585703f91426dcdf6b3
Author: Siyao Meng <50...@users.noreply.github.com>
AuthorDate: Thu Oct 22 11:50:11 2026 -0700

    HDDS-16164. DirectoryDeletingService could deadlock snapshot purge while retaining snapshot DB handles (#11009)
    
    Co-authored-by: Wei-Chiu Chuang <we...@apache.org>
---
 .../TestDirectoryDeletingServiceWithFSO.java       |   9 +-
 .../ozone/om/service/DirectoryDeletingService.java | 186 ++++++++---
 .../om/service/TestDirectoryDeletingService.java   | 357 ++++++++++++++++++++-
 3 files changed, 500 insertions(+), 52 deletions(-)

diff --git a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingServiceWithFSO.java b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingServiceWithFSO.java
index 4050ff0e0ca..04695b97e14 100644
--- a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingServiceWithFSO.java
+++ b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingServiceWithFSO.java
@@ -110,6 +110,7 @@ public class TestDirectoryDeletingServiceWithFSO {
   private int snapshotCountAfterTest = -1;
   private boolean pendingSdsResume = false;
   private DirectoryDeletingService pendingResumeDds = null;
+  private DirectoryDeletingService pendingShutdownDds = null;
   private boolean needsTableCleanup = false;
   private String snapshotCleanupVolume = null;
   private String snapshotCleanupBucket = null;
@@ -160,6 +161,10 @@ public static void teardown() {
   @AfterEach
   public void cleanup() throws Exception {
     try {
+      if (pendingShutdownDds != null) {
+        pendingShutdownDds.shutdown();
+        pendingShutdownDds = null;
+      }
       if (pendingSdsResume) {
         cluster.getOzoneManager().getKeyManager().getSnapshotDeletingService().resume();
         pendingSdsResume = false;
@@ -634,7 +639,7 @@ public void testAOSKeyDeletingWithSnapshotCreateParallelExecution()
     when(ozoneManager.getOmSnapshotManager()).thenAnswer(i -> omSnapshotManager);
     DirectoryDeletingService service = Mockito.spy(new DirectoryDeletingService(1000, TimeUnit.MILLISECONDS, 1000,
         ozoneManager, cluster.getConf(), 1, false));
-    service.shutdown();
+    pendingShutdownDds = service;
     final int initialSnapshotCount =
         (int) cluster.getOzoneManager().getMetadataManager().countRowsInTable(snapshotInfoTable);
     snapshotCountAfterTest = initialSnapshotCount;
@@ -673,7 +678,7 @@ public void testAOSKeyDeletingWithSnapshotCreateParallelExecution()
       return null;
     }).when(service).optimizeDirDeletesAndSubmitRequest(anyList(), anyList(), eq(null), anyLong(), any(),
         any(ReclaimableDirFilter.class), any(ReclaimableKeyFilter.class), anyMap(), any(),
-        anyLong(), any(AtomicInteger.class));
+        anyLong(), any(AtomicInteger.class), any());
 
     Mockito.doAnswer(i -> {
       store.createSnapshot(testVolumeName, testBucketName, snap2);
diff --git a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/DirectoryDeletingService.java b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/DirectoryDeletingService.java
index 7aebd9528a6..d258a79169f 100644
--- a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/DirectoryDeletingService.java
+++ b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/DirectoryDeletingService.java
@@ -43,12 +43,14 @@
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ForkJoinPool;
 import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.stream.Collectors;
@@ -130,7 +132,9 @@
  *
  * <h2>Threading and Parallelism</h2>
  * <ul>
- *   <li>Uses a configurable thread pool for parallel deletion tasks within each store/snapshot.</li>
+ *   <li>Uses a configurable thread pool for parallel deletion tasks within each store or snapshot.</li>
+ *   <li>Coordinates workers so each thread closes its own snapshot DB handles before submitting requests.</li>
+ *   <li>Runs one store task at a time; its workers process directories in parallel.</li>
  *   <li>Each snapshot and AOS get a separate background task for deletion.</li>
  * </ul>
  *
@@ -179,7 +183,9 @@ public DirectoryDeletingService(long interval, TimeUnit unit,
       long serviceTimeout, OzoneManager ozoneManager,
       OzoneConfiguration configuration, int dirDeletingServiceCorePoolSize, boolean deepCleanSnapshots) {
     super(DirectoryDeletingService.class.getSimpleName(), interval, unit,
-        dirDeletingServiceCorePoolSize, serviceTimeout, ozoneManager);
+        1, serviceTimeout, ozoneManager);
+    // ponytail: one store coordinator prevents tasks retaining DB handles while waiting for the shared worker pool.
+    // Concurrent stores would require coordinated DB-handle ownership and worker scheduling.
     int limit = (int) configuration.getStorageSize(
         OMConfigKeys.OZONE_OM_RATIS_LOG_APPENDER_QUEUE_BYTE_LIMIT,
         OMConfigKeys.OZONE_OM_RATIS_LOG_APPENDER_QUEUE_BYTE_LIMIT_DEFAULT,
@@ -220,7 +226,6 @@ void updateAndRestart(OzoneConfiguration conf) {
     shutdown();
     synchronized (this) {
       setInterval(newInterval, TimeUnit.SECONDS);
-      setPoolSize(newCorePoolSize);
       this.numberOfParallelThreadsPerStore.set(newCorePoolSize);
       start();
     }
@@ -314,10 +319,6 @@ private ThreadPoolExecutor createDeletionThreadPool(int threadCount) {
     return pool;
   }
 
-  private boolean isThreadPoolActive(ExecutorService threadPoolExecutor) {
-    return threadPoolExecutor != null && !threadPoolExecutor.isShutdown() && !threadPoolExecutor.isTerminated();
-  }
-
   @VisibleForTesting
   ThreadPoolExecutor getDeletionThreadPool() {
     return (ThreadPoolExecutor) deletionThreadPool;
@@ -332,7 +333,8 @@ void optimizeDirDeletesAndSubmitRequest(
       CheckedFunction<KeyValue<String, OmKeyInfo>, Boolean, IOException> reclaimableDirChecker,
       CheckedFunction<KeyValue<String, OmKeyInfo>, Boolean, IOException> reclaimableFileChecker,
       Map<VolumeBucketId, BucketNameInfo> bucketNameInfoMap,
-      UUID expectedPreviousSnapshotId, long rnCnt, AtomicInteger remainNum) {
+      UUID expectedPreviousSnapshotId, long rnCnt, AtomicInteger remainNum,
+      Runnable beforeSubmit) {
 
     // Optimization to handle delete sub-dir and keys to remove quickly
     // This case will be useful to handle when depth of directory is high
@@ -358,6 +360,8 @@ void optimizeDirDeletesAndSubmitRequest(
         break;
       }
     }
+    beforeSubmit.run();
+
     List<PurgePathRequest> submitted = submitPurgePathsWithBatching(purgePathRequestList, snapTableKey,
         expectedPreviousSnapshotId, bucketNameInfoMap);
     long dirNum = 0;
@@ -656,12 +660,16 @@ private OzoneManagerProtocolProtos.SetSnapshotPropertyRequest getSetSnapshotRequ
     }
 
     /**
+     * Processes deleted directories in one store with parallel workers and updates snapshot properties afterward.
+     * Must run on the store coordinator so another store cannot retain DB handles while waiting for workers.
      *
      * @param currentSnapshotInfo if null, deleted directories in AOS should be processed.
      * @param keyManager KeyManager of the underlying store.
+     * @param currentSnapshot task-owned snapshot handle, or null for AOS; closed before workers submit requests.
      */
     @VisibleForTesting
-    void processDeletedDirsForStore(SnapshotInfo currentSnapshotInfo, KeyManager keyManager, long rnCnt, int remainNum)
+    void processDeletedDirsForStore(SnapshotInfo currentSnapshotInfo, KeyManager keyManager,
+        UncheckedAutoCloseableSupplier<OmSnapshot> currentSnapshot, long rnCnt, int remainNum)
         throws IOException, ExecutionException, InterruptedException {
       String volume, bucket; String snapshotTableKey;
       if (currentSnapshotInfo != null) {
@@ -672,6 +680,8 @@ void processDeletedDirsForStore(SnapshotInfo currentSnapshotInfo, KeyManager key
         volume = null; bucket = null; snapshotTableKey = null;
       }
 
+      Map<UUID, Pair<Long, Long>> exclusiveSizeMap = Maps.newConcurrentMap();
+      boolean processedAllDeletedDirs;
       try (DeletedDirSupplier dirSupplier = new DeletedDirSupplier(currentSnapshotInfo == null ?
           keyManager.getDeletedDirEntries() : keyManager.getDeletedDirEntries(volume, bucket))) {
         // This is to avoid race condition b/w purge request and snapshot chain update. For AOS taking the global
@@ -680,44 +690,107 @@ void processDeletedDirsForStore(SnapshotInfo currentSnapshotInfo, KeyManager key
         UUID expectedPreviousSnapshotId = currentSnapshotInfo == null ?
             snapshotChainManager.getLatestGlobalSnapshotId() :
             SnapshotUtils.getPreviousSnapshotId(currentSnapshotInfo, snapshotChainManager);
-        Map<UUID, Pair<Long, Long>> exclusiveSizeMap = Maps.newConcurrentMap();
+        processedAllDeletedDirs = runDeletionWorkers(currentSnapshotInfo, keyManager, dirSupplier, currentSnapshot,
+            expectedPreviousSnapshotId, exclusiveSizeMap, rnCnt, remainNum);
+      }
+
+      // If AOS or all directories have been processed for snapshot, update snapshot size delta and deep clean flag
+      // if it is a snapshot. All snapshot DB iterators and handles have been closed before this synchronous request.
+      if (processedAllDeletedDirs) {
+        List<OzoneManagerProtocolProtos.SetSnapshotPropertyRequest> setSnapshotPropertyRequests = new ArrayList<>();
+
+        for (Map.Entry<UUID, Pair<Long, Long>> entry : exclusiveSizeMap.entrySet()) {
+          UUID snapshotID = entry.getKey();
+          long exclusiveSize = entry.getValue().getLeft();
+          long exclusiveReplicatedSize = entry.getValue().getRight();
+          setSnapshotPropertyRequests.add(getSetSnapshotRequestUpdatingExclusiveSize(
+              exclusiveSize, exclusiveReplicatedSize, snapshotID));
+        }
 
-        CompletableFuture<Boolean> processedAllDeletedDirs = CompletableFuture.completedFuture(true);
-        final int parallelThreads = numberOfParallelThreadsPerStore.get();
-        for (int i = 0; i < parallelThreads; i++) {
+        // Updating directory deep clean flag of snapshot.
+        if (currentSnapshotInfo != null) {
+          setSnapshotPropertyRequests.add(OzoneManagerProtocolProtos.SetSnapshotPropertyRequest.newBuilder()
+              .setSnapshotKey(snapshotTableKey)
+              .setDeepCleanedDeletedDir(true)
+              .build());
+        }
+        submitSetSnapshotRequests(setSnapshotPropertyRequests);
+      }
+    }
+
+    /**
+     * Waits for snapshot workers to close DB handles before opening the submission gate.
+     * The workers retain their GC locks through submission; the coordinator closes its own iterator and handle.
+     * AOS has no task-owned snapshot handle, so its workers can close their handles and submit independently.
+     */
+    @SuppressWarnings("checkstyle:ParameterNumber")
+    private boolean runDeletionWorkers(SnapshotInfo currentSnapshotInfo, KeyManager keyManager,
+        DeletedDirSupplier dirSupplier, UncheckedAutoCloseableSupplier<OmSnapshot> currentSnapshot,
+        UUID expectedPreviousSnapshotId, Map<UUID, Pair<Long, Long>> exclusiveSizeMap, long rnCnt, int remainNum)
+        throws ExecutionException, InterruptedException {
+      int parallelThreads = numberOfParallelThreadsPerStore.get();
+      CountDownLatch snapshotDbHandlesClosed = currentSnapshotInfo == null ? null : new CountDownLatch(parallelThreads);
+      CountDownLatch submitRequests = new CountDownLatch(1);
+      CompletableFuture<Boolean> workersCompleted = CompletableFuture.completedFuture(true);
+      for (int i = 0; i < parallelThreads; i++) {
+        AtomicBoolean workerReady = new AtomicBoolean();
+        try {
           CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
             try {
               return processDeletedDirectories(currentSnapshotInfo, keyManager, dirSupplier,
-                  expectedPreviousSnapshotId, exclusiveSizeMap, rnCnt, remainNum);
+                  expectedPreviousSnapshotId, exclusiveSizeMap, rnCnt, remainNum, () -> {
+                    if (snapshotDbHandlesClosed != null) {
+                      signalWorkerReady(workerReady, snapshotDbHandlesClosed);
+                      if (awaitUninterruptibly(submitRequests)) {
+                        Thread.currentThread().interrupt();
+                      }
+                    }
+                  });
             } catch (Throwable e) {
               return false;
+            } finally {
+              if (snapshotDbHandlesClosed != null) {
+                signalWorkerReady(workerReady, snapshotDbHandlesClosed);
+              }
             }
-          }, isThreadPoolActive(deletionThreadPool) ? deletionThreadPool : ForkJoinPool.commonPool());
-          processedAllDeletedDirs = processedAllDeletedDirs.thenCombine(future, (a, b) -> a && b);
-        }
-        // If AOS or all directories have been processed for snapshot, update snapshot size delta and deep clean flag
-        // if it is a snapshot.
-        if (processedAllDeletedDirs.get()) {
-          List<OzoneManagerProtocolProtos.SetSnapshotPropertyRequest> setSnapshotPropertyRequests = new ArrayList<>();
-
-          for (Map.Entry<UUID, Pair<Long, Long>> entry : exclusiveSizeMap.entrySet()) {
-            UUID snapshotID = entry.getKey();
-            long exclusiveSize = entry.getValue().getLeft();
-            long exclusiveReplicatedSize = entry.getValue().getRight();
-            setSnapshotPropertyRequests.add(getSetSnapshotRequestUpdatingExclusiveSize(
-                exclusiveSize, exclusiveReplicatedSize, snapshotID));
+          }, deletionThreadPool);
+          workersCompleted = workersCompleted.thenCombine(future, (a, b) -> a && b);
+        } catch (RejectedExecutionException e) {
+          // Account for the rejected worker and every remaining worker that will not be submitted.
+          if (snapshotDbHandlesClosed != null) {
+            countDown(snapshotDbHandlesClosed, parallelThreads - i);
           }
+          workersCompleted = workersCompleted.thenApply(ignored -> false);
+          break;
+        }
+      }
 
-          // Updating directory deep clean flag of snapshot.
-          if (currentSnapshotInfo != null) {
-            setSnapshotPropertyRequests.add(OzoneManagerProtocolProtos.SetSnapshotPropertyRequest.newBuilder()
-                .setSnapshotKey(snapshotTableKey)
-                .setDeepCleanedDeletedDir(true)
-                .build());
-          }
-          submitSetSnapshotRequests(setSnapshotPropertyRequests);
+      boolean interrupted = false;
+      if (currentSnapshot != null) {
+        interrupted = awaitUninterruptibly(snapshotDbHandlesClosed);
+        try {
+          dirSupplier.close();
+          currentSnapshot.close();
+        } finally {
+          submitRequests.countDown();
         }
       }
+
+      // Finish the accepted workers before the next store task can open a snapshot DB handle.
+      boolean processedAllDeletedDirs;
+      while (true) {
+        try {
+          processedAllDeletedDirs = workersCompleted.get();
+          break;
+        } catch (InterruptedException e) {
+          interrupted = true;
+        }
+      }
+      if (interrupted) {
+        Thread.currentThread().interrupt();
+        throw new InterruptedException();
+      }
+      return processedAllDeletedDirs;
     }
 
     /**
@@ -735,9 +808,11 @@ void processDeletedDirsForStore(SnapshotInfo currentSnapshotInfo, KeyManager key
      * @param remaining Number of dirs to be processed.
      * @return A boolean indicating whether the processed directory list is empty.
      */
+    @SuppressWarnings("checkstyle:ParameterNumber")
     private boolean processDeletedDirectories(SnapshotInfo currentSnapshotInfo, KeyManager keyManager,
         DeletedDirSupplier dirSupplier, UUID expectedPreviousSnapshotId,
-        Map<UUID, Pair<Long, Long>> totalExclusiveSizeMap, long runCount, int remaining) {
+        Map<UUID, Pair<Long, Long>> totalExclusiveSizeMap, long runCount, int remaining,
+        Runnable afterSnapshotDbHandlesClosed) {
       OmSnapshotManager omSnapshotManager = getOzoneManager().getOmSnapshotManager();
       IOzoneManagerLock lock = getOzoneManager().getMetadataManager().getLock();
       String snapshotTableKey = currentSnapshotInfo == null ? null : currentSnapshotInfo.getTableKey();
@@ -780,7 +855,14 @@ private boolean processDeletedDirectories(SnapshotInfo currentSnapshotInfo, KeyM
         optimizeDirDeletesAndSubmitRequest(allSubDirList, purgePathRequestList, snapshotTableKey,
             startTime, getOzoneManager().getKeyManager(),
             reclaimableDirFilter, reclaimableFileFilter, bucketNameInfos, expectedPreviousSnapshotId,
-            runCount, remainNum);
+            runCount, remainNum, () -> {
+              // Keep the snapshot GC locks until the purge requests complete, but release all snapshot DB read
+              // locks first. Otherwise a synchronous request can wait for the double buffer while the double
+              // buffer waits for a colliding snapshot DB write lock.
+              reclaimableDirFilter.closeSnapshotDbHandles();
+              reclaimableFileFilter.closeSnapshotDbHandles();
+              afterSnapshotDbHandlesClosed.run();
+            });
         Map<UUID, Long> exclusiveReplicatedSizeMap = reclaimableFileFilter.getExclusiveReplicatedSizeMap();
         Map<UUID, Long> exclusiveSizeMap = reclaimableFileFilter.getExclusiveSizeMap();
         List<UUID> previousPathSnapshotsInChain =
@@ -805,6 +887,30 @@ startTime, getOzoneManager().getKeyManager(),
       }
     }
 
+    private void signalWorkerReady(AtomicBoolean workerReady, CountDownLatch snapshotDbHandlesClosed) {
+      if (workerReady.compareAndSet(false, true)) {
+        snapshotDbHandlesClosed.countDown();
+      }
+    }
+
+    private void countDown(CountDownLatch latch, int count) {
+      for (int i = 0; i < count; i++) {
+        latch.countDown();
+      }
+    }
+
+    private boolean awaitUninterruptibly(CountDownLatch latch) {
+      boolean interrupted = false;
+      while (true) {
+        try {
+          latch.await();
+          return interrupted;
+        } catch (InterruptedException e) {
+          interrupted = true;
+        }
+      }
+    }
+
     @Override
     public BackgroundTaskResult call() {
       // Check if this is the Leader OM. If not leader, no need to execute this
@@ -840,7 +946,7 @@ public BackgroundTaskResult call() {
                   snapInfo.getName())) {
             KeyManager keyManager = snapInfo == null ? getOzoneManager().getKeyManager()
                 : omSnapshot.get().getKeyManager();
-            processDeletedDirsForStore(snapInfo, keyManager, run, pathLimitPerTask);
+            processDeletedDirsForStore(snapInfo, keyManager, omSnapshot, run, pathLimitPerTask);
           }
         } catch (IOException | ExecutionException e) {
           LOG.error("Error while running delete files background task for store {}. Will retry at next run.",
diff --git a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingService.java b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingService.java
index 12447b37cce..ff859e6077f 100644
--- a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingService.java
+++ b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestDirectoryDeletingService.java
@@ -18,10 +18,17 @@
 package org.apache.hadoop.ozone.om.service;
 
 import static org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor.ONE;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_BLOCK_DELETING_SERVICE_INTERVAL;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_MANAGER_STRIPED_LOCK_SIZE_PREFIX;
+import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_SNAPSHOT_DELETING_SERVICE_INTERVAL;
 import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_DIR_DELETING_SERVICE_INTERVAL;
+import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_PATH_DELETING_LIMIT_PER_TASK;
 import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_THREAD_NUMBER_DIR_DELETION;
+import static org.apache.hadoop.ozone.om.lock.DAGLeveledResource.SNAPSHOT_DB_LOCK;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 
 import com.google.protobuf.ServiceException;
 import java.io.File;
@@ -37,8 +44,16 @@
 import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.Semaphore;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.Pair;
@@ -46,6 +61,7 @@
 import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.conf.StorageUnit;
+import org.apache.hadoop.hdds.scm.HddsWhiteboxTestUtils;
 import org.apache.hadoop.hdds.server.ServerUtils;
 import org.apache.hadoop.hdds.utils.db.DBConfigFromFile;
 import org.apache.hadoop.ozone.ClientVersion;
@@ -53,6 +69,8 @@
 import org.apache.hadoop.ozone.om.KeyManager;
 import org.apache.hadoop.ozone.om.OMConfigKeys;
 import org.apache.hadoop.ozone.om.OMMetadataManager;
+import org.apache.hadoop.ozone.om.OmSnapshot;
+import org.apache.hadoop.ozone.om.OmSnapshotManager;
 import org.apache.hadoop.ozone.om.OmTestManagers;
 import org.apache.hadoop.ozone.om.OzoneManager;
 import org.apache.hadoop.ozone.om.helpers.BucketLayout;
@@ -60,7 +78,11 @@
 import org.apache.hadoop.ozone.om.helpers.OmDirectoryInfo;
 import org.apache.hadoop.ozone.om.helpers.OmKeyArgs;
 import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
+import org.apache.hadoop.ozone.om.helpers.OmVolumeArgs;
+import org.apache.hadoop.ozone.om.helpers.SnapshotInfo;
 import org.apache.hadoop.ozone.om.protocol.OzoneManagerProtocol;
+import org.apache.hadoop.ozone.om.ratis.OzoneManagerDoubleBuffer;
+import org.apache.hadoop.ozone.om.ratis.utils.OzoneManagerRatisUtils;
 import org.apache.hadoop.ozone.om.request.OMRequestTestUtils;
 import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
 import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
@@ -68,7 +90,9 @@
 import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.PurgePathRequest;
 import org.apache.hadoop.util.Time;
 import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ratis.protocol.ClientId;
 import org.apache.ratis.util.ExitUtils;
+import org.apache.ratis.util.function.UncheckedAutoCloseableSupplier;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.DisplayName;
@@ -76,6 +100,7 @@
 import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
 import org.mockito.Mockito;
 
 /**
@@ -233,7 +258,7 @@ public void testMultithreadedDirectoryDeletion() throws Exception {
       assertThat(threadPoolExecutor.isShutdown()).as(
           "deletion thread pool should be active when processing deleted dirs").isFalse();
       long completedTaskCountBefore = threadPoolExecutor.getCompletedTaskCount();
-      dirDeletingTask.processDeletedDirsForStore(null, ozoneManager.getKeyManager(), 1, 1);
+      dirDeletingTask.processDeletedDirsForStore(null, ozoneManager.getKeyManager(), null, 1, 1);
       GenericTestUtils.waitFor(
           () -> threadPoolExecutor.getCompletedTaskCount() >= completedTaskCountBefore + threadCount, 100, 5000);
     } finally {
@@ -256,14 +281,16 @@ void testUpdateAndRestart() throws Exception {
     updatedConf.setTimeDuration(OZONE_DIR_DELETING_SERVICE_INTERVAL, newInterval.toMillis(), TimeUnit.MILLISECONDS);
 
     assertThat(subject.getExecutorService().getCorePoolSize())
-        .as("initial thread pool size")
-        .isEqualTo(threadCount);
+        .as("one store coordinator before reconfiguration")
+        .isEqualTo(1);
+    assertThat(subject.getDeletionThreadPool().getCorePoolSize()).isEqualTo(threadCount);
 
     subject.updateAndRestart(updatedConf);
 
     assertThat(subject.getExecutorService().getCorePoolSize())
-        .as("thread pool size after restart")
-        .isEqualTo(newThreadCount);
+        .as("one store coordinator after reconfiguration")
+        .isEqualTo(1);
+    assertThat(subject.getDeletionThreadPool().getCorePoolSize()).isEqualTo(newThreadCount);
     assertThat(subject.getIntervalMillis())
         .as("interval after restart")
         .isEqualTo(newInterval.toMillis());
@@ -317,7 +344,7 @@ void testPurgeDirectoriesSubmitFailure(int failedBatch, boolean throwException,
 
       subject.optimizeDirDeletesAndSubmitRequest(Collections.emptyList(), purgeList, snapshotKey,
           Time.monotonicNow(), keyManager, kv -> true, kv -> true, Collections.emptyMap(), null, 1,
-          new AtomicInteger(0));
+          new AtomicInteger(0), () -> { });
 
       assertThat(submitted).hasSize(failedBatch);
       int successfulBatches = failedBatch - 1;
@@ -339,7 +366,7 @@ void testPurgeDirectoriesSubmitFailure(int failedBatch, boolean throwException,
       subject.getTasks();
       subject.optimizeDirDeletesAndSubmitRequest(Collections.emptyList(), remaining, snapshotKey,
           Time.monotonicNow(), keyManager, kv -> true, kv -> true, Collections.emptyMap(), null, 2,
-          new AtomicInteger(0));
+          new AtomicInteger(0), () -> { });
 
       assertThat(submitted).hasSize(failedBatch + remaining.size());
       for (int i = 0; i < remaining.size(); i++) {
@@ -401,7 +428,7 @@ void testPurgeDirectoriesRecursiveAccounting(int failedBatch, int expectedBatche
       }).when(subject).submitRequest(Mockito.any(OMRequest.class));
 
       subject.optimizeDirDeletesAndSubmitRequest(subDirs, purgeList, null, Time.monotonicNow(), keyManager,
-          kv -> true, kv -> true, Collections.emptyMap(), null, 1, new AtomicInteger(10));
+          kv -> true, kv -> true, Collections.emptyMap(), null, 1, new AtomicInteger(10), () -> { });
 
       assertThat(submitted).hasSize(expectedBatches);
       assertThat(subject.getDeletedDirsCount()).isEqualTo(expectedDeletedDirs);
@@ -470,7 +497,7 @@ void testPurgeDirectoriesBatching() throws Exception {
     bucketNameInfoMap.put(vbId, bni);
 
     dds.optimizeDirDeletesAndSubmitRequest(new ArrayList<>(), purgeList, null, Time.monotonicNow(), km,
-        kv -> true, kv -> true, bucketNameInfoMap, null, 1L, new AtomicInteger(Integer.MAX_VALUE));
+        kv -> true, kv -> true, bucketNameInfoMap, null, 1L, new AtomicInteger(Integer.MAX_VALUE), () -> { });
 
     assertThat(captured.size())
         .as("Expect batching to respect Ratis byte limit")
@@ -530,7 +557,7 @@ void testPurgeDirectoriesGroupedByBucketPerTransaction() throws Exception {
     }
 
     dds.optimizeDirDeletesAndSubmitRequest(new ArrayList<>(), purgeList, null, Time.monotonicNow(), km,
-        kv -> true, kv -> true, bucketNameInfoMap, null, 1L, new AtomicInteger(Integer.MAX_VALUE));
+        kv -> true, kv -> true, bucketNameInfoMap, null, 1L, new AtomicInteger(Integer.MAX_VALUE), () -> { });
 
     assertThat(captured).as("Expect one transaction per bucket when the byte limit is not hit").hasSize(2);
     Set<Long> bucketsSeen = new HashSet<>();
@@ -545,4 +572,314 @@ void testPurgeDirectoriesGroupedByBucketPerTransaction() throws Exception {
         bucketIdA, bucketIdB);
   }
 
+  /**
+   * Regression test for HDDS-16164. Snapshot workers must wait for the task-owned handle to close before submitting.
+   * AOS workers own their handles and can finish scanning while a sibling waits for double-buffer capacity.
+   * A worker failure with DB handles open must also release its handles and let the remaining workers finish.
+   */
+  @ParameterizedTest(name = "activeStore={0}, workerThrows={1}")
+  @CsvSource({"false, false", "true, false", "false, true", "true, true"})
+  @DisplayName("DirectoryDeletingService must not deadlock at the unflushed transaction limit")
+  void testNoUnflushedTransactionDeadlock(boolean activeStore, boolean workerThrows) throws Exception {
+    int threadCount = 3;
+    OzoneConfiguration conf = createConfAndInitValues(threadCount);
+    conf.setInt(OMConfigKeys.OZONE_OM_UNFLUSHED_TRANSACTION_MAX_COUNT, 1);
+    conf.setInt(OZONE_PATH_DELETING_LIMIT_PER_TASK, 1);
+    conf.setInt(OZONE_MANAGER_STRIPED_LOCK_SIZE_PREFIX + "snapshot_db_lock", 1);
+    conf.setTimeDuration(OZONE_BLOCK_DELETING_SERVICE_INTERVAL, 1, TimeUnit.HOURS);
+    conf.setTimeDuration(OZONE_SNAPSHOT_DELETING_SERVICE_INTERVAL, 1, TimeUnit.HOURS);
+    conf.setTimeDuration(OZONE_DIR_DELETING_SERVICE_INTERVAL, 1, TimeUnit.HOURS);
+
+    OmTestManagers managers = new OmTestManagers(conf);
+    om = managers.getOzoneManager();
+    KeyManager keyManager = managers.getKeyManager();
+    OMMetadataManager metadataManager = managers.getMetadataManager();
+    OzoneManagerProtocol writeClient = managers.getWriteClient();
+    keyManager.getDirDeletingService().shutdown();
+
+    OMRequestTestUtils.addVolumeToOM(metadataManager,
+        OmVolumeArgs.newBuilder().setOwnerName("o").setAdminName("a").setVolume(volumeName).build());
+    OMRequestTestUtils.addBucketToOM(metadataManager,
+        OmBucketInfo.newBuilder().setVolumeName(volumeName).setBucketName(bucketName)
+            .setObjectID(1).setBucketLayout(BucketLayout.FILE_SYSTEM_OPTIMIZED).build());
+
+    SnapshotInfo deepCleanInfo = prepareSnapshotsForDeadlock(writeClient, metadataManager, threadCount, activeStore);
+    String purgeKey = SnapshotInfo.getTableKey(volumeName, bucketName, "purge");
+
+    OzoneManager ozoneManager = Mockito.spy(om);
+    OmSnapshotManager snapshotManager = Mockito.spy(om.getOmSnapshotManager());
+    Mockito.doReturn(snapshotManager).when(ozoneManager).getOmSnapshotManager();
+    AtomicInteger openSnapshotDbHandles = new AtomicInteger();
+    trackSnapshotDbHandles(snapshotManager, openSnapshotDbHandles);
+
+    AtomicInteger purgeRequests = new AtomicInteger();
+    AtomicBoolean submittedWithDbLock = new AtomicBoolean();
+    CountDownLatch ddsAtSubmit = new CountDownLatch(1);
+    CountDownLatch ddsMayProceed = new CountDownLatch(1);
+    DirectoryDeletingService service = Mockito.spy(new DirectoryDeletingService(1, TimeUnit.HOURS, 1,
+        ozoneManager, conf, threadCount, true) {
+      @Override
+      protected OzoneManagerProtocolProtos.OMResponse submitRequest(
+          OzoneManagerProtocolProtos.OMRequest omRequest) throws ServiceException {
+        assertThat(omRequest.getCmdType()).isIn(
+            OzoneManagerProtocolProtos.Type.PurgeDirectories,
+            OzoneManagerProtocolProtos.Type.SetSnapshotProperty);
+        if (metadataManager.getLock().getReadHoldCount(SNAPSHOT_DB_LOCK,
+            deepCleanInfo.getSnapshotId().toString()) != 0 || (!activeStore && openSnapshotDbHandles.get() != 0)) {
+          submittedWithDbLock.set(true);
+        }
+        if (omRequest.getCmdType() == OzoneManagerProtocolProtos.Type.PurgeDirectories) {
+          purgeRequests.incrementAndGet();
+        }
+        ddsAtSubmit.countDown();
+        try {
+          ddsMayProceed.await();
+        } catch (InterruptedException e) {
+          Thread.currentThread().interrupt();
+          throw new ServiceException(e);
+        }
+        return super.submitRequest(omRequest);
+      }
+    });
+
+    CountDownLatch workersPrepared = new CountDownLatch(threadCount);
+    CountDownLatch finishScanning = new CountDownLatch(1);
+    AtomicBoolean pauseScan = new AtomicBoolean();
+    AtomicBoolean workerFailureInjected = new AtomicBoolean();
+    Mockito.doAnswer(invocation -> {
+      workersPrepared.countDown();
+      if (pauseScan.compareAndSet(false, true)) {
+        // Keep this worker's previous-snapshot handle open while the other workers finish scanning.
+        assertThat(metadataManager.getLock().getReadHoldCount(SNAPSHOT_DB_LOCK,
+            deepCleanInfo.getSnapshotId().toString())).isPositive();
+        assertTrue(finishScanning.await(30, TimeUnit.SECONDS));
+        if (workerThrows) {
+          workerFailureInjected.set(true);
+          throw new IllegalStateException("Injected failure with previous-snapshot DB handles open");
+        }
+      }
+      return invocation.callRealMethod();
+    }).when(service).optimizeDirDeletesAndSubmitRequest(
+        Mockito.anyList(), Mockito.anyList(), Mockito.any(), Mockito.anyLong(), Mockito.any(), Mockito.any(),
+        Mockito.any(), Mockito.anyMap(), Mockito.any(), Mockito.anyLong(), Mockito.any(), Mockito.any());
+
+    OzoneManagerDoubleBuffer doubleBuffer = om.getOmRatisServer().getOmStateMachine().getOzoneManagerDoubleBuffer();
+    Semaphore unflushedTransactions =
+        (Semaphore) HddsWhiteboxTestUtils.getInternalState(doubleBuffer, "unFlushedTransactions");
+    ThreadPoolExecutor deletionThreadPool = service.getDeletionThreadPool();
+    long completedTaskCountBefore = deletionThreadPool.getCompletedTaskCount();
+    ExecutorService executor = Executors.newFixedThreadPool(2);
+    try {
+      Future<?> ddsFuture = service.getExecutorService().submit(
+          () -> service.new DirDeletingTask(activeStore ? null : deepCleanInfo.getSnapshotId()).call());
+      assertTrue(workersPrepared.await(30, TimeUnit.SECONDS), "Expected all configured workers to scan in parallel");
+      if (!activeStore) {
+        assertThat(ddsAtSubmit.await(200, TimeUnit.MILLISECONDS))
+            .as("snapshot workers must wait for the task-owned snapshot handle to close").isFalse();
+        finishScanning.countDown();
+      }
+      assertTrue(ddsAtSubmit.await(30, TimeUnit.SECONDS), "DirDeletingTask never reached submitRequest");
+
+      CountDownLatch nextStoreStarted = new CountDownLatch(1);
+      Future<?> nextStore = service.getExecutorService().submit(nextStoreStarted::countDown);
+      assertThat(nextStoreStarted.await(200, TimeUnit.MILLISECONDS))
+          .as("the next store must not open DB handles while workers are submitting requests").isFalse();
+
+      AtomicBoolean purgeDone = new AtomicBoolean();
+      OzoneManagerProtocolProtos.OMRequest purgeRequest = OzoneManagerProtocolProtos.OMRequest.newBuilder()
+          .setCmdType(OzoneManagerProtocolProtos.Type.SnapshotPurge)
+          .setSnapshotPurgeRequest(OzoneManagerProtocolProtos.SnapshotPurgeRequest.newBuilder()
+              .addSnapshotDBKeys(purgeKey))
+          .setClientId(ClientId.randomId().toString())
+          .build();
+      Future<?> purgeFuture = executor.submit(() -> {
+        OzoneManagerRatisUtils.submitRequest(om, purgeRequest, ClientId.randomId(), 1L);
+        purgeDone.set(true);
+        return null;
+      });
+      GenericTestUtils.waitFor(() -> unflushedTransactions.availablePermits() == 0 || purgeDone.get(), 50, 30000);
+
+      ddsMayProceed.countDown();
+      if (activeStore) {
+        GenericTestUtils.waitFor(unflushedTransactions::hasQueuedThreads, 50, 10000);
+      }
+      // An AOS worker can finish scanning and close its handle even while a sibling waits for flush capacity.
+      finishScanning.countDown();
+      try {
+        ddsFuture.get(60, TimeUnit.SECONDS);
+      } catch (TimeoutException e) {
+        fail("DirectoryDeletingService retained a snapshot DB read lock across its synchronous OM request");
+      }
+      purgeFuture.get(60, TimeUnit.SECONDS);
+      nextStore.get(10, TimeUnit.SECONDS);
+      om.awaitDoubleBufferFlush();
+      GenericTestUtils.waitFor(() -> deletionThreadPool.getCompletedTaskCount() ==
+          completedTaskCountBefore + threadCount, 100, 5000);
+      assertThat(deletionThreadPool.getCompletedTaskCount() - completedTaskCountBefore)
+          .as("store processing should use all configured deletion workers").isEqualTo(threadCount);
+      int expectedPurges = workerThrows ? threadCount - 1 : threadCount;
+      assertThat(workerFailureInjected.get()).isEqualTo(workerThrows);
+      assertThat(purgeRequests).hasValue(expectedPurges);
+      assertThat(submittedWithDbLock).as("snapshot DB locks must be released before submitting requests").isFalse();
+      assertThat(openSnapshotDbHandles).as("all handles must close, including after a worker failure").hasValue(0);
+      assertThat(service.getDeletedDirsCount()).isEqualTo(expectedPurges);
+    } finally {
+      finishScanning.countDown();
+      ddsMayProceed.countDown();
+      executor.shutdownNow();
+      service.shutdown();
+    }
+  }
+
+  @ParameterizedTest(name = "stoppedExecutor={0}")
+  @ValueSource(booleans = {false, true})
+  @DisplayName("DirectoryDeletingService releases snapshot workers when submission is rejected")
+  void testRejectedSnapshotWorkerSubmission(boolean stoppedExecutor) throws Exception {
+    OzoneConfiguration conf = createConfAndInitValues(3);
+    OmTestManagers managers = new OmTestManagers(conf);
+    om = managers.getOzoneManager();
+    KeyManager keyManager = managers.getKeyManager();
+    OMMetadataManager metadataManager = managers.getMetadataManager();
+    OzoneManagerProtocol writeClient = managers.getWriteClient();
+    keyManager.getDirDeletingService().shutdown();
+
+    OMRequestTestUtils.addVolumeToOM(metadataManager,
+        OmVolumeArgs.newBuilder().setOwnerName("o").setAdminName("a").setVolume(volumeName).build());
+    OMRequestTestUtils.addBucketToOM(metadataManager,
+        OmBucketInfo.newBuilder().setVolumeName(volumeName).setBucketName(bucketName)
+            .setObjectID(1).setBucketLayout(BucketLayout.FILE_SYSTEM_OPTIMIZED).build());
+    String snapshotName = "snapshot";
+    writeClient.createSnapshot(volumeName, bucketName, snapshotName);
+    om.awaitDoubleBufferFlush();
+
+    String snapshotKey = SnapshotInfo.getTableKey(volumeName, bucketName, snapshotName);
+    SnapshotInfo snapshotInfo = metadataManager.getSnapshotInfoTable().get(snapshotKey);
+    assertNotNull(snapshotInfo);
+    awaitSnapshotFlushed(metadataManager, snapshotInfo);
+
+    DirectoryDeletingService service = new DirectoryDeletingService(1, TimeUnit.HOURS, 1,
+        om, conf, 3, true);
+    RejectAfterFirstExecutor rejectionExecutor = new RejectAfterFirstExecutor();
+    if (stoppedExecutor) {
+      rejectionExecutor.shutdown();
+    }
+    HddsWhiteboxTestUtils.setInternalState(service, "deletionThreadPool", rejectionExecutor);
+    ExecutorService taskExecutor = Executors.newSingleThreadExecutor();
+    try {
+      Future<?> processFuture = taskExecutor.submit(() -> {
+        try (UncheckedAutoCloseableSupplier<OmSnapshot> snapshot = om.getOmSnapshotManager().getActiveSnapshot(
+            volumeName, bucketName, snapshotName)) {
+          service.new DirDeletingTask(snapshotInfo.getSnapshotId()).processDeletedDirsForStore(snapshotInfo,
+              snapshot.get().getKeyManager(), snapshot, 1, 1);
+        }
+        return null;
+      });
+      processFuture.get(10, TimeUnit.SECONDS);
+      int expectedCompletedTasks = stoppedExecutor ? 0 : 1;
+      GenericTestUtils.waitFor(() -> rejectionExecutor.getCompletedTaskCount() == expectedCompletedTasks, 100, 5000);
+      assertThat(rejectionExecutor.getCompletedTaskCount()).isEqualTo(expectedCompletedTasks);
+    } finally {
+      taskExecutor.shutdownNow();
+      service.shutdown();
+    }
+  }
+
+  private SnapshotInfo prepareSnapshotsForDeadlock(OzoneManagerProtocol writeClient, OMMetadataManager metadataManager,
+      int threadCount, boolean activeStore) throws Exception {
+    writeClient.createSnapshot(volumeName, bucketName, "purge");
+    writeClient.createSnapshot(volumeName, bucketName, "previous");
+    String deepCleanSnapshotName = "deep-clean";
+    if (activeStore) {
+      writeClient.createSnapshot(volumeName, bucketName, deepCleanSnapshotName);
+    }
+    om.awaitDoubleBufferFlush();
+
+    addDeletedDirectories(metadataManager, threadCount);
+    if (!activeStore) {
+      writeClient.createSnapshot(volumeName, bucketName, deepCleanSnapshotName);
+    }
+    om.awaitDoubleBufferFlush();
+
+    String deepCleanKey = SnapshotInfo.getTableKey(volumeName, bucketName, deepCleanSnapshotName);
+    SnapshotInfo deepCleanInfo = metadataManager.getSnapshotInfoTable().get(deepCleanKey);
+    assertNotNull(deepCleanInfo);
+    awaitSnapshotFlushed(metadataManager, deepCleanInfo);
+
+    writeClient.deleteSnapshot(volumeName, bucketName, "purge");
+    om.awaitDoubleBufferFlush();
+    assertNotNull(metadataManager.getSnapshotInfoTable().get(
+        SnapshotInfo.getTableKey(volumeName, bucketName, "purge")));
+    return deepCleanInfo;
+  }
+
+  private void trackSnapshotDbHandles(OmSnapshotManager snapshotManager, AtomicInteger openSnapshotDbHandles)
+      throws IOException {
+    Mockito.doAnswer(invocation -> {
+      UncheckedAutoCloseableSupplier<OmSnapshot> delegate =
+          (UncheckedAutoCloseableSupplier<OmSnapshot>) invocation.callRealMethod();
+      openSnapshotDbHandles.incrementAndGet();
+      return new UncheckedAutoCloseableSupplier<OmSnapshot>() {
+        private final AtomicBoolean closed = new AtomicBoolean();
+
+        @Override
+        public OmSnapshot get() {
+          return delegate.get();
+        }
+
+        @Override
+        public void close() {
+          if (closed.compareAndSet(false, true)) {
+            delegate.close();
+            openSnapshotDbHandles.decrementAndGet();
+          }
+        }
+      };
+    }).when(snapshotManager).getActiveSnapshot(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
+  }
+
+  private void addDeletedDirectories(OMMetadataManager metadataManager, int count) throws Exception {
+    OmBucketInfo bucketInfo = metadataManager.getBucketTable()
+        .get(metadataManager.getBucketKey(volumeName, bucketName));
+    for (int i = 0; i < count; i++) {
+      OmDirectoryInfo deletedDir = OmDirectoryInfo.newBuilder()
+          .setName("deleted-dir-" + i)
+          .setCreationTime(Time.now())
+          .setModificationTime(Time.now())
+          .setObjectID(2 + i)
+          .setParentObjectID(bucketInfo.getObjectID())
+          .setUpdateID(0)
+          .build();
+      String deletedDirKey = OMRequestTestUtils.addDirKeyToDirTable(
+          false, deletedDir, volumeName, bucketName, 1L, metadataManager);
+      OMRequestTestUtils.deleteDir(deletedDirKey, volumeName, bucketName, metadataManager);
+    }
+  }
+
+  private void awaitSnapshotFlushed(OMMetadataManager metadataManager, SnapshotInfo snapshotInfo) throws Exception {
+    GenericTestUtils.waitFor(() -> {
+      try {
+        return OmSnapshotManager.areSnapshotChangesFlushedToDB(metadataManager, snapshotInfo);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }, 100, 10000);
+  }
+
+  private static final class RejectAfterFirstExecutor extends ThreadPoolExecutor {
+    private final AtomicInteger submittedTaskCount = new AtomicInteger();
+
+    private RejectAfterFirstExecutor() {
+      super(1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
+    }
+
+    @Override
+    public void execute(Runnable task) {
+      if (submittedTaskCount.getAndIncrement() == 0) {
+        super.execute(task);
+      } else {
+        throw new RejectedExecutionException("Rejected by test executor");
+      }
+    }
+  }
+
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@ozone.apache.org
For additional commands, e-mail: commits-help@ozone.apache.org