3838import java .util .concurrent .Executors ;
3939import java .util .concurrent .TimeUnit ;
4040import java .util .concurrent .atomic .AtomicInteger ;
41+ import java .util .concurrent .atomic .AtomicReference ;
4142import java .util .concurrent .locks .Lock ;
4243
4344import org .junit .Test ;
@@ -118,8 +119,7 @@ public void testConcurrentReads() throws InterruptedException {
118119 // With ReentrantReadWriteLock, we should see true concurrent reads
119120 assertTrue ("Multiple readers should have been reading concurrently" , maxConcurrentReaders .get () > 1 );
120121
121- // Time should be much less than sequential execution (numReaders *
122- // 100ms)
122+ // Time should be much less than sequential execution (numReaders * 100ms)
123123 assertTrue ("Concurrent execution should be faster than sequential" , duration < numReaders * 100 );
124124 }
125125
@@ -162,7 +162,7 @@ public void testReadWriteExclusion() throws InterruptedException {
162162 }
163163
164164 @ Test
165- public void testTryLock () {
165+ public void testTryLock () throws InterruptedException {
166166
167167 KeyLock keyLock = new KeyLock ();
168168 String testKey = "test-key" ;
@@ -187,9 +187,16 @@ public void testTryLock() {
187187 writeLock = keyLock .tryLockForWriting (testKey );
188188 assertNotNull ("Should acquire write lock after reads are released" , writeLock );
189189
190- // // Try acquiring read lock while write is held - should fail
191- // Lock readLock3 = keyLock.tryLockForReading(testKey);
192- // assertNull("Should not acquire read lock while write is held", readLock3);
190+ // Try acquiring read lock from another thread while write is held - should fail
191+ // Because
192+ AtomicReference <Lock > readLock3 = new AtomicReference <>();
193+ Thread readerThread = new Thread (() -> {
194+ readLock3 .set (keyLock .tryLockForReading (testKey ));
195+ });
196+ readerThread .start ();
197+ readerThread .join ();
198+
199+ assertNull ("Should not acquire read lock while write is held" , readLock3 .get ());
193200
194201 writeLock .unlock ();
195202 }
0 commit comments