View Javadoc

1   package net.sf.ehcache.concurrent;
2   
3   import org.junit.Before;
4   import org.junit.Test;
5   
6   import static org.junit.Assert.assertFalse;
7   import static org.junit.Assert.assertSame;
8   import static org.junit.Assert.assertTrue;
9   
10  /***
11   * @author Alex Snaps
12   */
13  public class StripedReadWriteLockSyncTest {
14      private Object[] keys;
15      private CacheLockProvider clp;
16  
17      @Before
18      public void setUp() throws Exception {
19          keys = new Object[]{new StupidKey(0), new StupidKey(0)};
20          clp = new StripedReadWriteLockSync(2);
21      }
22  
23      @Test
24      public void testIsProperlyReentrant() {
25  
26          Sync syncForKey = clp.getSyncForKey(keys[0]);
27  
28          assertSame(syncForKey, clp.getSyncForKey(keys[1]));
29  
30          clp.getAndWriteLockAllSyncForKeys(keys);
31          for (Object key : keys) {
32              assertTrue(syncForKey.isHeldByCurrentThread(LockType.WRITE));
33              clp.getSyncForKey(key).unlock(LockType.WRITE);
34              if (key != keys[keys.length - 1]) {
35                  assertTrue(syncForKey.isHeldByCurrentThread(LockType.WRITE));
36              }
37          }
38  
39          assertFalse(syncForKey.isHeldByCurrentThread(LockType.WRITE));
40      }
41  
42      @Test
43      public void testIsProperlyUnlockingAllKeys() {
44          Sync syncForKey = clp.getSyncForKey(keys[0]);
45  
46          assertSame(syncForKey, clp.getSyncForKey(keys[1]));
47  
48          clp.getAndWriteLockAllSyncForKeys(keys);
49          clp.unlockWriteLockForAllKeys(keys);
50  
51          assertFalse(syncForKey.isHeldByCurrentThread(LockType.WRITE));
52      }
53  
54      private static final class StupidKey {
55          private final int hashCode;
56  
57          private StupidKey(final int hashCode) {
58              this.hashCode = hashCode;
59          }
60  
61          @Override
62          public int hashCode() {
63              return hashCode;
64          }
65      }
66  }