ZKGlobalMutexFactory implements GlobalMutexFactory, AutoCloseable { @Override public GlobalMutex acquire() throws GlobalMutexAcquireException { int potentialValue = ZKGlobalMutexFactory.nextPotentialValue(); for (int i = 0; i < RANGE; i++) { potentialValue += i; if ( potentialValue > RANGE ) potentialValue = 0; ZKGlobalMutex result = acquire( potentialValue ); if ( result != null ) { acquired.add( result ); return result; } } throw new GlobalMutexAcquireException( "Unable to acquire mutex. Too many allocated." ); } ZKGlobalMutexFactory( String connectString,
                                 int connectionTimeout,
                                 int sessionTimeout,
                                 String namespace ); @Override void close(); @Override GlobalMutex acquire(); static final int RANGE; }
@Test public void testAcquire() throws Exception { ZKGlobalMutexFactory zkGlobalMutexFactory = zkGlobalMutexFactoryProvider.get(); assertNotNull( zkGlobalMutexFactory.acquire( 0 ) ); assertNull( zkGlobalMutexFactory.acquire( 0 ) ); assertNotNull( zkGlobalMutexFactory.acquire( 1 ) ); GlobalMutex mutex = zkGlobalMutexFactory.acquire(); assertNotNull( mutex ); assertFalse( mutex.isExpired() ); zkGlobalMutexFactory.close(); assertTrue( mutex.isExpired() ); }
@Test(expected = GlobalMutexAcquireException.class) @Ignore public void testLocksExhausted() throws Exception { ZKGlobalMutexFactory zkGlobalMutexFactory = zkGlobalMutexFactoryProvider.get(); for (int i = 0; i < ZKGlobalMutexFactory.RANGE * 2; ++i) { zkGlobalMutexFactory.acquire(); } }
@Test public void testFullLockRange() throws Exception { ZKGlobalMutexFactory zkGlobalMutexFactory = zkGlobalMutexFactoryProvider.get(); for (int i = 0; i < ZKGlobalMutexFactory.RANGE; ++i) { zkGlobalMutexFactory.acquire(i); } }
@Test(expected = GlobalMutexAcquireException.class) public void testTestFullLockRangeWithFailure() throws Exception { ZKGlobalMutexFactory zkGlobalMutexFactory = zkGlobalMutexFactoryProvider.get(); for (int i = 0; i < ZKGlobalMutexFactory.RANGE; ++i) { zkGlobalMutexFactory.acquire(i); } zkGlobalMutexFactory.acquire(); }