ZKNamedMutexFactory implements NamedMutexFactory, AutoCloseable { @Override public NamedMutex acquire( String name ) throws NamedMutexException { Preconditions.checkNotNull( name ); try { String potentialPath = BASEDIR + "/" + name; curatorClient.create() .withMode( CreateMode.EPHEMERAL ) .forPath( potentialPath ) ; log.info( "Acquired named mutex: %s" , name ); return new ZKNamedMutex( curatorClient, potentialPath ); } catch ( KeeperException.NodeExistsException e ) { log.info( "Failed to acquire named mutex: %s" , name ); throw new NamedMutexException.AcquireException( "Unable to acquire mutex: " + name ); } catch ( Exception e ) { throw new NamedMutexException.FailureException( "Unable to acquire mutex: " + name, e ); } } ZKNamedMutexFactory(String connectString,
                               int connectionTimeout,
                               int sessionTimeout,
                               String namespace ); @Override NamedMutex acquire( String name ); @Override void close();  }
@Test public void testBasicAcquireThenRelease() throws Exception { NamedMutexFactory namedMutexFactory = namedMutexFactoryProvider.get(); try( NamedMutex namedMutex = namedMutexFactory.acquire( "testmutex" ); ) { System.out.printf( "within the mutex... \n" ); } try( NamedMutex namedMutex = namedMutexFactory.acquire( "testmutex" ); ) { System.out.printf( "within the mutex... second time. \n" ); } }
@Test( expected = NamedMutexException.AcquireException.class ) public void testDoubleAcquireWithFailure() throws Exception { NamedMutexFactory namedMutexFactory = namedMutexFactoryProvider.get(); namedMutexFactory.acquire( "testmutex" ); namedMutexFactory.acquire( "testmutex" ); }