Test Overview
This test demonstrates how to use @ResourceLock in JUnit to prevent concurrent access to a shared resource. It verifies that two test methods do not run at the same time on the same resource, avoiding conflicts.
This test demonstrates how to use @ResourceLock in JUnit to prevent concurrent access to a shared resource. It verifies that two test methods do not run at the same time on the same resource, avoiding conflicts.
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.api.parallel.Resources; import static org.junit.jupiter.api.Assertions.assertTrue; public class ResourceLockTest { private static int sharedCounter = 0; @Test @ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceLock.Mode.READ) void testReadLock() throws InterruptedException { int before = sharedCounter; Thread.sleep(100); // Simulate read operation int after = sharedCounter; assertTrue(before == after, "Shared counter should not change during read lock"); } @Test @ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceLock.Mode.WRITE) void testWriteLock() throws InterruptedException { int before = sharedCounter; sharedCounter++; Thread.sleep(100); // Simulate write operation int after = sharedCounter; assertTrue(after == before + 1, "Shared counter should increment by 1 during write lock"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and prepares to run testReadLock | No tests running, sharedCounter = 0 | - | PASS |
| 2 | testReadLock acquires READ lock on SYSTEM_PROPERTIES resource | Lock acquired, testReadLock running | - | PASS |
| 3 | testReadLock reads sharedCounter value (0), sleeps 100ms simulating read | sharedCounter = 0, testReadLock active | - | PASS |
| 4 | testReadLock asserts sharedCounter unchanged during read lock | sharedCounter still 0 | assertTrue(before == after) | PASS |
| 5 | testReadLock releases READ lock | No locks held | - | PASS |
| 6 | Test runner starts testWriteLock | No tests running, sharedCounter = 0 | - | PASS |
| 7 | testWriteLock acquires WRITE lock on SYSTEM_PROPERTIES resource | Lock acquired, testWriteLock running | - | PASS |
| 8 | testWriteLock reads sharedCounter (0), increments it to 1, sleeps 100ms simulating write | sharedCounter = 1, testWriteLock active | - | PASS |
| 9 | testWriteLock asserts sharedCounter incremented by 1 during write lock | sharedCounter = 1 | assertTrue(after == before + 1) | PASS |
| 10 | testWriteLock releases WRITE lock | No locks held | - | PASS |