private <T> Optional<T> tryWithLock(
      long timeout, TimeUnit unit, boolean interruptOnClose, Supplier<T> task) {
    checkLockNotHeld("Lock cannot be reacquired");

    boolean acquired = false;
    try {
      acquired = exclusiveLock.tryLock(timeout, unit, interruptOnClose);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }

    if (!acquired) {
      return Optional.empty();
    }

    T result = null;
    Throwable failure = null;
    try {
      result = task.get();
      // opportunistic check to avoid unnecessary lock reacquisition
      destroyIfNecessary();
    } catch (Throwable t) {
      failure = t;
    } finally {
      exclusiveLock.unlock();
    }

    // We need to recheck whether the state is NEED_DESTRUCTION, if so, destroy the driver.
    // We assume that there is another concurrent Thread-A calling close method, it successfully CAS
    // state from ALIVE to NEED_DESTRUCTION just after current Thread-B do destroyIfNecessary() and
    // before exclusiveLock.unlock().
    // Then Thread-A call this method, trying to acquire lock and do destroy things, but it won't
    // succeed because the lock is still held by Thread-B. So Thread-A exit.
    // If we don't do this recheck here, Thread-B will exit too. Nobody will do destroy things.
    if (state.get() == State.NEED_DESTRUCTION && exclusiveLock.tryLock(interruptOnClose)) {
      try {
        destroyIfNecessary();
      } catch (Throwable t) {
        if (failure == null) {
          failure = t;
        } else if (failure != t) {
          failure.addSuppressed(t);
        }
      } finally {
        exclusiveLock.unlock();
      }
    }

    if (failure != null) {
      throwIfUnchecked(failure);
      // should never happen
      throw new AssertionError(failure);
    }

    verify(result != null, "result is null");
    return Optional.of(result);
  }
Try to acquire the {@code exclusiveLock} with {@code timeout} and run a {@code task}. If the
{@code interruptOnClose} flag is set to {@code true} the {@code task} will be interrupted if
the {@code Driver} is closed.

<p>Note: task cannot return null
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/driver/Driver.java