/** * Acquires a distributed lock through ZooKeeper. It's the same as calling * {@link #acquire(boolean, boolean, long, java.util.concurrent.TimeUnit)} with {@link Long#MAX_VALUE} as timeout. */ private boolean acquire(boolean interruptible, boolean waitForLock) throws InterruptedException, ExecutionException { try { return acquire(interruptible, waitForLock, Long.MAX_VALUE, TimeUnit.SECONDS); } catch (TimeoutException e) { // Should never happen throw Throwables.propagate(e); } }
@Override public void lock() { lock.lock(); try { acquire(false, true); } catch (Exception e) { lock.unlock(); throw Throwables.propagate(e); } }
@Override public boolean tryLock() { if (!lock.tryLock()) { return false; } try { if (acquire(false, false)) { return true; } lock.unlock(); return false; } catch (Exception e) { lock.unlock(); throw Throwables.propagate(e); } }
@Override public void lockInterruptibly() throws InterruptedException { lock.lockInterruptibly(); try { acquire(true, true); } catch (Exception e) { lock.unlock(); Throwables.propagateIfInstanceOf(e, InterruptedException.class); throw Throwables.propagate(e); } }
@Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { long startTime = System.nanoTime(); if (!lock.tryLock(time, unit)) { return false; } long timeoutNano = unit.toNanos(time) - (System.nanoTime() - startTime); try { if (acquire(true, true, timeoutNano, TimeUnit.NANOSECONDS)) { return true; } lock.unlock(); return false; } catch (ExecutionException e) { lock.unlock(); throw Throwables.propagate(e.getCause()); } catch (TimeoutException e) { lock.unlock(); return false; } }