rpuch commented on code in PR #4233: URL: https://github.com/apache/ignite-3/pull/4233#discussion_r1718665236
########## modules/core/src/test/java/org/apache/ignite/internal/util/VersatileReadWriteLockTest.java: ########## @@ -0,0 +1,606 @@ +/* + * 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.ignite.internal.util; + +import static java.lang.Thread.currentThread; +import static java.util.concurrent.CompletableFuture.allOf; +import static java.util.concurrent.CompletableFuture.anyOf; +import static java.util.concurrent.CompletableFuture.completedFuture; +import static java.util.concurrent.CompletableFuture.failedFuture; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.apache.ignite.internal.testframework.IgniteTestUtils.runRace; +import static org.apache.ignite.internal.testframework.IgniteTestUtils.waitForCondition; +import static org.apache.ignite.internal.testframework.matchers.CompletableFutureExceptionMatcher.willThrow; +import static org.apache.ignite.internal.testframework.matchers.CompletableFutureExceptionMatcher.willTimeoutIn; +import static org.apache.ignite.internal.testframework.matchers.CompletableFutureMatcher.willBe; +import static org.apache.ignite.internal.testframework.matchers.CompletableFutureMatcher.willCompleteSuccessfully; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.ignite.internal.lang.RunnableX; +import org.apache.ignite.internal.logger.IgniteLogger; +import org.apache.ignite.internal.logger.Loggers; +import org.apache.ignite.internal.thread.NamedThreadFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junitpioneer.jupiter.cartesian.CartesianTest; +import org.junitpioneer.jupiter.cartesian.CartesianTest.Enum; + +/** + * Tests for {@link VersatileReadWriteLock}. + */ +@Timeout(20) +class VersatileReadWriteLockTest { + private static final IgniteLogger LOG = Loggers.forClass(VersatileReadWriteLockTest.class); + + private static final String ASYNC_CONTINUATION_THREAD_PREFIX = "ace"; + + private final ExecutorService asyncContinuationExecutor = Executors.newCachedThreadPool( + new NamedThreadFactory(ASYNC_CONTINUATION_THREAD_PREFIX, LOG) + ); + + /** The lock under test. */ + private final VersatileReadWriteLock lock = new VersatileReadWriteLock(asyncContinuationExecutor); + + /** Executor service used to run tasks in threads different from the main test thread. */ + private final ExecutorService executor = Executors.newCachedThreadPool(); + + /** + * Cleans up after a test. + */ + @AfterEach + void cleanup() { + releaseReadLocks(); + releaseWriteLocks(); + + IgniteUtils.shutdownAndAwaitTermination(executor, 3, SECONDS); + IgniteUtils.shutdownAndAwaitTermination(asyncContinuationExecutor, 3, SECONDS); + } + + private void releaseReadLocks() { + while (true) { + try { + lock.readUnlock(); + } catch (IllegalMonitorStateException e) { + // Released our read lock completely. + break; + } + } + } + + private void releaseWriteLocks() { + while (true) { + try { + lock.writeUnlock(); + } catch (IllegalMonitorStateException e) { + // Released our write lock completely. + break; + } + } + } + + @ParameterizedTest + @EnumSource(BlockingWriteLockAcquisition.class) + void readLockDoesNotAllowWriteLockToBeAcquired(BlockingWriteLockAcquisition acquisition) { + lock.readLock(); + + assertThatWriteLockAcquireAttemptBlocksForever(acquisition); + + lock.readUnlock(); + } + + @ParameterizedTest + @EnumSource(BlockingWriteLockAcquisition.class) + void readLockDoesNotAllowWriteLockToBeAcquiredBySameThread(BlockingWriteLockAcquisition acquisition) { + assertThatActionBlocksForever(() -> { + lock.readLock(); + acquisition.acquire(lock); + }); + + lock.readUnlock(); + } + + private void assertThatWriteLockAcquireAttemptBlocksForever(BlockingWriteLockAcquisition acquisition) { + assertThatActionBlocksForever(() -> acquisition.acquire(lock)); + } + + private void assertThatActionBlocksForever(Runnable action) { + Future<?> future = executor.submit(action); + + assertThrows(TimeoutException.class, () -> future.get(100, MILLISECONDS)); + } + + @Test + void readLockDoesNotAllowWriteLockToBeAcquiredWithTimeout() throws Exception { + lock.readLock(); + + Boolean acquired = callWithTimeout(() -> lock.tryWriteLock(1, MILLISECONDS)); + assertThat(acquired, is(false)); + + lock.readUnlock(); + } + + @Test + void readLockDoesNotAllowWriteLockToBeAcquiredWithTimeoutBySameThread() throws Exception { + Boolean acquired = callWithTimeout(() -> { + lock.readLock(); + return lock.tryWriteLock(1, MILLISECONDS); + }); + assertThat(acquired, is(false)); + + lock.readUnlock(); + } + + @Test + void readLockAllowsReadLockToBeAcquired() throws Exception { + lock.readLock(); + + assertThatReadLockCanBeAcquired(); + } + + private void assertThatReadLockCanBeAcquired() throws InterruptedException, ExecutionException, TimeoutException { + runWithTimeout(lock::readLock); + } + + private <T> T callWithTimeout(Callable<T> call) throws ExecutionException, InterruptedException, TimeoutException { + Future<T> future = executor.submit(call); + return getWithTimeout(future); + } + + private void runWithTimeout(Runnable runnable) throws ExecutionException, InterruptedException, TimeoutException { + Future<?> future = executor.submit(runnable); + getWithTimeout(future); + } + + private static <T> T getWithTimeout(Future<? extends T> future) throws ExecutionException, + InterruptedException, TimeoutException { + return future.get(10, SECONDS); + } + + @ParameterizedTest + @EnumSource(BlockingWriteLockAcquisition.class) + void writeLockDoesNotAllowReadLockToBeAcquired(BlockingWriteLockAcquisition acquisition) { + acquisition.acquire(lock); + + assertThatReadLockAcquireAttemptBlocksForever(); + + lock.writeUnlock(); + } + + private void assertThatReadLockAcquireAttemptBlocksForever() { + assertThatActionBlocksForever(lock::readLock); + } + + @ParameterizedTest + @EnumSource(BlockingWriteLockAcquisition.class) + void writeLockDoesNotAllowReadLockToBeAcquiredBySameThread(BlockingWriteLockAcquisition acquisition) { + assertThatActionBlocksForever(() -> { + acquisition.acquire(lock); + lock.readLock(); + }); + + lock.writeUnlock(); + } + + @CartesianTest + @EnumSource(BlockingWriteLockAcquisition.class) + void writeLockDoesNotAllowWriteLockToBeAcquired( + @Enum(BlockingWriteLockAcquisition.class) BlockingWriteLockAcquisition firstAttempt, + @Enum(BlockingWriteLockAcquisition.class) BlockingWriteLockAcquisition secondAttempt + ) { + firstAttempt.acquire(lock); + + assertThatWriteLockAcquireAttemptBlocksForever(secondAttempt); + + lock.writeUnlock(); + } + + @CartesianTest + @EnumSource(BlockingWriteLockAcquisition.class) + void writeLockDoesNotAllowWriteLockToBeAcquiredBySameThread( + @Enum(BlockingWriteLockAcquisition.class) BlockingWriteLockAcquisition firstAttempt, + @Enum(BlockingWriteLockAcquisition.class) BlockingWriteLockAcquisition secondAttempt + ) { + assertThatActionBlocksForever(() -> { + firstAttempt.acquire(lock); + secondAttempt.acquire(lock); + }); + + lock.writeUnlock(); + } + + @Test + void readUnlockReleasesTheLock() throws Exception { + lock.readLock(); + lock.readUnlock(); + + runWithTimeout(lock::writeLock); + } + + @ParameterizedTest + @EnumSource(BlockingWriteLockAcquisition.class) + void writeUnlockReleasesTheLock(BlockingWriteLockAcquisition acquisition) throws Exception { + acquisition.acquire(lock); + lock.writeUnlock(); + + assertThatReadLockCanBeAcquired(); + } + + @Test + void shouldNotAllowInterleavingHoldingReadAndWriteLocks() { + lock.writeLock(); + + assertFalse(lock.tryReadLock()); + + lock.writeUnlock(); + + lock.readLock(); + + assertFalse(lock.tryWriteLock()); + + lock.readUnlock(); + + // Test that we can operate with write locks now. + lock.writeLock(); + lock.writeUnlock(); + } + + @Test + void readLockReleasedLessTimesThanAcquiredShouldStillBeTaken() throws Exception { + lock.readLock(); + + Future<?> future = executor.submit(() -> { + lock.readLock(); + lock.readUnlock(); + }); + future.get(10, SECONDS); Review Comment: Changed everywhere except for one case where a `Callable` is passed. `CompletableFuture.supplyAsync()` does not align well with something that can throw a checked exception. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
