List of usage examples for org.apache.zookeeper ZooKeeper create
public String create(final String path, byte[] data, List<ACL> acl, CreateMode createMode) throws KeeperException, InterruptedException
From source file:ch.usi.da.paxos.Util.java
License:Open Source License
/** * This method fixes the race condition faced by the client when checking if * a znode already exists before creating one. It basically handles the * <b>NodeExistsException</b>, if an exception handler was given, or ignore * it, otherwise.//w ww. ja va 2 s. com * * @param path * the path for the node * @param data * the initial data for the node * @param acl * the acl for the node * @param createMode * specifying whether the node to be created is ephemeral * and/or sequential * @param zooClient * a ZooKeeper client object * @param exceptionHandler * the object that will handle the NodeExistsExcpetion; if this * is null, the exception is ignored and the execution continues * without replacing the already existing znode * @return the actual path of the created node * @throws KeeperException if the server returns a non-zero error code * @throws KeeperException.InvalidACLException if the ACL is invalid, null, or empty * @throws InterruptedException if the transaction is interrupted * @throws IllegalArgumentException if an invalid path is specified */ public static String checkThenCreateZooNode(final String path, byte data[], List<ACL> acl, CreateMode createMode, ZooKeeper zooClient, ExceptionListener exceptionHandler) throws KeeperException, InterruptedException { String createReturn = null; try { createReturn = zooClient.create(path, data, acl, createMode); } catch (NodeExistsException e) { if (exceptionHandler != null) { exceptionHandler.exceptionThrown(e); } } return createReturn; }
From source file:com.andyadc.menagerie.collections.ZkListSet.java
License:Apache License
@Override public boolean add(T t) { acquireWriteLock();//w w w. j ava2 s. com try { ZooKeeper zk = sessionManager.getZooKeeper(); List<String> children = ZkUtils.filterByPrefix(zk.getChildren(baseNode, false), prefix()); for (String child : children) { byte[] data = ZkUtils.safeGetData(zk, baseNode + "/" + child, false, new Stat()); if (data.length > 0) { if (serializer.deserialize(data).equals(t)) return false; } } zk.create(baseNode + "/" + prefix() + delimiter(), serializer.serialize(t), privileges, CreateMode.PERSISTENT_SEQUENTIAL); return true; } catch (InterruptedException e) { throw new RuntimeException(e); } catch (KeeperException e) { throw new RuntimeException(e); } finally { releaseWriteLock(); } }
From source file:com.andyadc.menagerie.latches.ZkCountDownLatch.java
License:Apache License
private void ensureState() { ensureNodeExists();/*from w w w .ja va2 s . c o m*/ ZooKeeper zooKeeper = zkSessionManager.getZooKeeper(); //TODO -sf- is there a non-blocking way to do this? Lock lock = new ReentrantZkLock(baseNode, zkSessionManager, privileges); try { lock.lock(); if (zooKeeper.exists(baseNode + "/countDown-latchReady", false) == null) { clearState(zooKeeper, latchPrefix); zooKeeper.create(baseNode + "/countDown-latchReady", emptyNode, privileges, CreateMode.PERSISTENT); } } catch (KeeperException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { lock.unlock(); } }
From source file:com.andyadc.menagerie.latches.ZkSemaphore.java
License:Apache License
/** * Acquires the given number of permits from this semaphore, blocking until all is available * <p>/* w ww . ja v a 2 s .c o m*/ * If all permits are immediately available, this method returns immediately, reducing the number of available * permits in the semaphore by the number requested. * <p> * If insufficient permits are available, this thread becomes disables and lies dormant until some * other thread invokes the {@link #release()} method (equivalently, until some other party * leaves abruptly, as in a node failure scenario), the current party is the next to be assigned to a permit, * and the number of available permits is sufficient to satisfy this request. * <p> * This method will ignore interruptions entirely. If the current Thread is interrupted, this method will continue * to wait. When it does return, its interrupt status will be set. * * @param permits the number of permits to acquire */ public void acquireUninterruptibly(int permits) { setConnectionListener(); ZooKeeper zk = zkSessionManager.getZooKeeper(); String[] permitNodes = new String[permits]; try { for (int i = 0; i < permitNodes.length; i++) { permitNodes[i] = zk.create(baseNode + "/" + permitPrefix + permitDelimiter, emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL); } while (true) { if (broken) throw new RuntimeException("Connection to ZooKeeper expired while waiting for a permit"); localLock.lock(); try { boolean acquiredPermits = false; for (String permitNode : permitNodes) { acquiredPermits = acquiredPermits || tryAcquireDistributed(zk, permitNode, true); } if (!acquiredPermits) { condition.awaitUninterruptibly(); } else return; } finally { localLock.unlock(); } } } catch (KeeperException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { removeConnectionListener(); } }
From source file:com.andyadc.menagerie.latches.ZkSemaphore.java
License:Apache License
/** * Acquires the given number of permits from this semaphore <i>only<i/> if sufficient permits are available * at the time of invocation.//from w ww.ja va 2s . c om * <p> * If all permits are immediately available, this method returns {@code true} immediately, reducing the number of * available permits in the semaphore by the number of permits requested. * <p> * If insufficient permits are available then this method will return immediately with the value {@code false}. * <p> * Note: Unlike {@link java.util.concurrent.Semaphore#tryAcquire()}, this method <i>will</i> obey ordering policies, * and will <i>never</i> acquire a permit at the expense of another party. * * @param permits the number of permits to acquire * @return true if a permit has been acquired, false otherwise */ public boolean tryAcquire(int permits) { ZooKeeper zk = zkSessionManager.getZooKeeper(); String[] permitNodes = new String[permits]; try { for (int i = 0; i < permitNodes.length; i++) { permitNodes[i] = zk.create(baseNode + "/" + permitPrefix + permitDelimiter, emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL); } localLock.lock(); try { boolean acquiredPermits = false; for (String permitNode : permitNodes) { acquiredPermits = acquiredPermits || tryAcquireDistributed(zk, permitNode, false); } if (!acquiredPermits) { //delete all my nodes to indicate that I'm giving up ZkUtils.safeDeleteAll(zk, -1, permitNodes); return false; } return true; } finally { localLock.unlock(); } } catch (KeeperException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:com.andyadc.menagerie.latches.ZkSemaphore.java
License:Apache License
/** * Acquires the given number of permits from this semaphore if a sufficient number become available within * the given waiting time and the current thread has not been interrupted. * <p>//from w ww . ja v a 2s.com * If enough permits are immediately available, this method returns {@code true} immediately, * reducing the number of available permits in the semaphore by the number requested. * <p> * If insufficient permits are available, then the current thread becomes disabled and lies dormant until one of the * following occurs: * <ul> * <li>Some other party invokes the {@link #release()} method for this semaphore, the current party * is the next to be assigned a permit, and sufficient permits are available to satisfy this request * <li>Some other thread interrupts the current thread * <li>The specified waiting time elapses * </ul> * <p> * If the current thread: * <ul> * <li> has its interrupted status set on entry to this method or * <li> is interrupted while waiting for a permit * </ul> * then an InterruptedException is thrown and the current thread's interrupted status is cleared. * <p> * If the specified waiting time elapses before enough permits are acquired, then {@code false} is returned, and * any permits which have been granted to this party are released back to the semaphore. If enough permits are * obtained before the time has elapsed fully, {@code true} is returned. * * @param permits the number of permits to acquire * @param timeout the maximum time to wait for a permit * @param unit the time unit to count in * @return true if a permit has been acquired within the specified time, false otherwise * @throws InterruptedException if the current thread is interrupted */ public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); setConnectionListener(); ZooKeeper zk = zkSessionManager.getZooKeeper(); String[] permitNodes = new String[permits]; try { for (int i = 0; i < permitNodes.length; i++) { permitNodes[i] = zk.create(baseNode + "/" + permitPrefix + permitDelimiter, emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL); } long timeoutNanos = unit.toNanos(timeout); while (true) { if (broken) throw new InterruptedException("Connection to ZooKeeper expired while waiting for a permit"); else if (Thread.interrupted()) { //delete our permitNodes ZkUtils.safeDeleteAll(zk, -1, permitNodes); throw new InterruptedException(); } else if (timeoutNanos <= 0) { //delete our permitNodes ZkUtils.safeDeleteAll(zk, -1, permitNodes); return false; } localLock.lock(); try { boolean acquiredPermits = false; for (String permitNode : permitNodes) { acquiredPermits = acquiredPermits || tryAcquireDistributed(zk, permitNode, true); } if (!acquiredPermits) { timeoutNanos = condition.awaitNanos(timeoutNanos); } else return true; } finally { localLock.unlock(); } } } catch (KeeperException e) { throw new RuntimeException(e); } finally { removeConnectionListener(); } }
From source file:com.andyadc.menagerie.locks.ReentrantZkLock.java
License:Apache License
/** * Acquires the lock./*from w w w . jav a 2s . c o m*/ * <p><p> * If the lock is not available, then the current thread becomes disabled for thread scheduling purposes and * lies dormant until the lock as been acquired. * <p><p> * Note: If the ZooKeeper session expires while this method is waiting, a {@link RuntimeException} will be thrown. * * @throws RuntimeException wrapping: * <ul> * <li> {@link KeeperException} if the ZooKeeper server * encounters a problem * <li> {@link InterruptedException} if there is a communication problem between * the ZooKeeper client and server * <li> If the ZooKeeper session expires * </ul> * @inheritDoc * @see Lock#lock() */ @Override public final void lock() { if (checkReentrancy()) return; //set a connection listener to listen for session expiration setConnectionListener(); ZooKeeper zk = zkSessionManager.getZooKeeper(); String lockNode; try { lockNode = zk.create(getBaseLockPath(), emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL); while (true) { if (broken) throw new RuntimeException("ZooKeeper Session has expired, invalidating this lock object"); localLock.lock(); try { //ask ZooKeeper for the lock boolean acquiredLock = tryAcquireDistributed(zk, lockNode, true); if (!acquiredLock) { //we don't have the lock, so we need to wait for our watcher to fire //this method is not interruptible, so need to wait appropriately condition.awaitUninterruptibly(); } else { //we have the lock, so return happy locks.set(new LockHolder(lockNode)); return; } } finally { localLock.unlock(); } } } catch (KeeperException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { //we no longer care about having a ConnectionListener here removeConnectionListener(); } }
From source file:com.andyadc.menagerie.locks.ReentrantZkLock.java
License:Apache License
/** * Acquires the lock only if it is free at the time of invocation. * <p><p>//from ww w. ja v a 2 s .c o m * Note: If the ZooKeeper Session expires while this thread is processing, nothing is required to happen. * * @return true if the lock has been acquired, false otherwise * @throws RuntimeException wrapping : * <ul> * <li>{@link KeeperException} if there is trouble * processing a request with the ZooKeeper servers. * <li> {@link InterruptedException} if there is an error communicating between the ZooKeeper client and servers. * </ul> * @inheritDoc */ @Override public final boolean tryLock() { if (checkReentrancy()) return true; ZooKeeper zk = zkSessionManager.getZooKeeper(); try { String lockNode = zk.create(getBaseLockPath(), emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL); //try to determine its position in the queue boolean lockAcquired = tryAcquireDistributed(zk, lockNode, false); if (!lockAcquired) { //we didn't get the lock, so return false zk.delete(lockNode, -1); return false; } else { //we have the lock, so it goes on the queue locks.set(new LockHolder(lockNode)); return true; } } catch (KeeperException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:com.andyadc.menagerie.locks.ReentrantZkLock.java
License:Apache License
/** * Acquires the lock only if it is free within the given waiting time and the current thread has not been * interrupted./* ww w .j a v a 2s . c o m*/ * <p><p> * Note: If the ZooKeeper Session expires while this thread is waiting, an {@link InterruptedException} will be * thrown. * * @param time the maximum time to wait, in milliseconds * @param unit the TimeUnit to use * @return true if the lock is acquired before the timeout expires * @throws InterruptedException if one of the four following conditions hold: * <ol> * <li value="1">The Thread is interrupted upon entry to the method * <li value="2">Another thread interrupts this thread while it is waiting to acquire the lock * <li value="3">There is a communication problem between the ZooKeeper client and the ZooKeeper server. * <li value="4">The ZooKeeper session expires and invalidates this lock. * </ol> * @inheritDoc * @see #tryLock(long, TimeUnit) */ @Override public final boolean tryLock(long time, TimeUnit unit) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (checkReentrancy()) return true; ZooKeeper zk = zkSessionManager.getZooKeeper(); //add a connection listener setConnectionListener(); String lockNode; try { lockNode = zk.create(getBaseLockPath(), emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL); while (true) { if (Thread.interrupted()) { zk.delete(lockNode, -1); throw new InterruptedException(); } else if (broken) { throw new InterruptedException("The ZooKeeper Session expired and invalidated this lock"); } boolean localAcquired = localLock.tryLock(time, unit); try { if (!localAcquired) { //delete the lock node and return false zk.delete(lockNode, -1); return false; } //ask ZooKeeper for the lock boolean acquiredLock = tryAcquireDistributed(zk, lockNode, true); if (!acquiredLock) { //we don't have the lock, so we need to wait for our watcher to fire boolean alerted = condition.await(time, unit); if (!alerted) { //we timed out, so delete the node and return false zk.delete(lockNode, -1); return false; } } else { //we have the lock, so return happy locks.set(new LockHolder(lockNode)); return true; } } finally { localLock.unlock(); } } } catch (KeeperException e) { throw new RuntimeException(e); } finally { //don't care about the connection any more removeConnectionListener(); } }
From source file:com.andyadc.menagerie.locks.ZkCondition.java
License:Apache License
@Override public void awaitUninterruptibly() { if (!distributedLock.hasLock()) throw new IllegalMonitorStateException("await was called without owning the associated lock"); //put a signal node onto zooKeeper, then wait for it to be deleted try {// w w w .j a va2 s .c o m ZooKeeper zooKeeper = zkSessionManager.getZooKeeper(); String conditionName = zooKeeper.create(baseNode + "/" + conditionPrefix + conditionDelimiter, emptyNode, privileges, CreateMode.EPHEMERAL_SEQUENTIAL); //now release the associated zkLock distributedLock.unlock(); while (true) { localLock.lock(); try { if (zooKeeper.exists(conditionName, signalWatcher) == null) { //we have been signalled, so relock and then return distributedLock.lock(); return; } else { condition.awaitUninterruptibly(); } } finally { localLock.unlock(); } } } catch (KeeperException e) { throw new RuntimeException(e); } catch (InterruptedException e) { //this can only be thrown by ZooKeeper utilities, which indicates that a //communication error between ZkServers and ZkClients occurred, so we had better throw it throw new RuntimeException(e); } }