private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedException {
    while (true) {
      // Acquire locks
      boolean gotFirstLock = false;
      boolean gotSecondLock = false;

      try {
        /**
         * tryLock() which will only acquire a lock if it’s available and not already acquired by
         * another thread and tryLock(long time,TimeUnit unit), which will try to acquire a lock
         * and, if it's unavailable wait for the specified timer to expire before giving up
         */
        gotFirstLock = firstLock.tryLock();
        gotSecondLock = secondLock.tryLock();
      } finally {
        if (gotFirstLock && gotSecondLock) {
          return;
        }
        if (gotFirstLock) {
          firstLock.unlock();
        }
        if (gotSecondLock) {
          secondLock.unlock();
        }
      }

      // Locks not acquired
      Thread.sleep(1);
    }
  }
Пример #2
0
 @SuppressWarnings("LockAcquiredButNotSafelyReleased")
 protected void handleLock(String[] args) {
   String lockStr = args[0];
   String key = args[1];
   Lock lock = hazelcast.getLock(key);
   if (lockStr.equalsIgnoreCase("lock")) {
     lock.lock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("unlock")) {
     lock.unlock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("trylock")) {
     String timeout = args.length > 2 ? args[2] : null;
     if (timeout == null) {
       println(lock.tryLock());
     } else {
       long time = Long.valueOf(timeout);
       try {
         println(lock.tryLock(time, TimeUnit.SECONDS));
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
   }
 }
Пример #3
0
  private MemoryLockToken getLock(String resource, Type type, long wait)
      throws InterruptedException {
    ReentrantReadWriteLock lockEntry;
    synchronized (locks) {
      if (locks.containsKey(resource)) {
        lockEntry = locks.get(resource);
      } else {
        lockEntry = new ReentrantReadWriteLock(true);
        locks.put(resource, lockEntry);
      }
    }

    Lock lock = (type.equals(Type.READ)) ? lockEntry.readLock() : lockEntry.writeLock();

    if (wait == -1) {
      lock.lock();
    } else {
      if (wait > 0) {
        if (!lock.tryLock(wait, TimeUnit.MILLISECONDS)) {
          return null;
        }
      } else {
        if (!lock.tryLock()) {
          return null;
        }
      }
    }
    synchronized (locks) {
      if (!locks.containsKey(resource)) {
        locks.put(resource, lockEntry);
      }
    }
    return new MemoryLockToken(lockEntry, lock, resource);
  }
  /** @throws Exception If test fails. */
  public void testMultiNodeLock() throws Exception {
    IgniteCache<Integer, String> cache1 = ignite1.cache(null);
    IgniteCache<Integer, String> cache2 = ignite2.cache(null);

    Lock lock1_1 = cache1.lock(1);
    Lock lock2_1 = cache2.lock(1);

    lock1_1.lock();

    try {
      assert cache1.isLocalLocked(1, false) : entries(1);
      assert cache1.isLocalLocked(1, true);

      assert cache2.isLocalLocked(1, false) : entries(1);
      assert !cache2.isLocalLocked(1, true);

      assert !lock2_1.tryLock();

      assert cache2.isLocalLocked(1, false) : entries(1);
      assert !cache2.isLocalLocked(1, true);
    } finally {
      lock1_1.unlock();

      checkUnlocked(cache1, 1);
    }

    CountDownLatch latch = new CountDownLatch(1);

    lock2_1.lock();

    try {
      assert cache2.isLocalLocked(1, false) : entries(1);
      assert cache2.isLocalLocked(1, true);

      assert cache1.isLocalLocked(1, false) : entries(1);
      assert !cache1.isLocalLocked(1, true);

      addListener(ignite1, new UnlockListener(latch, 1));

      assert !lock1_1.tryLock();

      assert cache1.isLocalLocked(1, false) : entries(1);
      assert !cache1.isLocalLocked(1, true);
    } finally {
      lock2_1.unlock();
    }

    latch.await();

    checkUnlocked(cache1, 1);
    checkUnlocked(cache2, 1);
  }
Пример #5
0
 private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedException {
   while (true) {
     boolean gotFirstLock = false;
     boolean gotSecondLock = false;
     try {
       gotFirstLock = firstLock.tryLock();
       gotSecondLock = secondLock.tryLock();
     } finally {
       if (gotFirstLock && gotSecondLock) return;
       else if (gotFirstLock) firstLock.unlock();
       else if (gotSecondLock) secondLock.unlock();
     }
     Thread.sleep(1);
   }
 }
Пример #6
0
  private boolean addEntry(
      final Feed feed, final FeedEntry entry, final List<FeedSubscription> subscriptions) {
    boolean success = false;

    // lock on feed, make sure we are not updating the same feed twice at
    // the same time
    String key1 = StringUtils.trimToEmpty("" + feed.getId());

    // lock on content, make sure we are not updating the same entry
    // twice at the same time
    FeedEntryContent content = entry.getContent();
    String key2 =
        DigestUtils.sha1Hex(StringUtils.trimToEmpty(content.getContent() + content.getTitle()));

    Iterator<Lock> iterator = locks.bulkGet(Arrays.asList(key1, key2)).iterator();
    Lock lock1 = iterator.next();
    Lock lock2 = iterator.next();
    boolean locked1 = false;
    boolean locked2 = false;
    try {
      locked1 = lock1.tryLock(1, TimeUnit.MINUTES);
      locked2 = lock2.tryLock(1, TimeUnit.MINUTES);
      if (locked1 && locked2) {
        feedUpdateService.updateEntry(feed, entry);
        List<User> users = Lists.newArrayList();
        for (FeedSubscription sub : subscriptions) {
          users.add(sub.getUser());
        }
        cache.invalidateUnreadCount(subscriptions.toArray(new FeedSubscription[0]));
        cache.invalidateUserRootCategory(users.toArray(new User[0]));
        metricsBean.entryInserted();
        success = true;
      } else {
        log.error("lock timeout for " + feed.getUrl() + " - " + key1);
      }
    } catch (InterruptedException e) {
      log.error(
          "interrupted while waiting for lock for " + feed.getUrl() + " : " + e.getMessage(), e);
    } finally {
      if (locked1) {
        lock1.unlock();
      }
      if (locked2) {
        lock2.unlock();
      }
    }
    return success;
  }
Пример #7
0
 @Override
 public V get(long timeout, TimeUnit unit)
     throws InterruptedException, TimeoutException, ExecutionException {
   long tryLockStart = System.currentTimeMillis();
   if (!lock.tryLock(timeout, unit)) {
     throw new TimeoutException();
   }
   try {
     if (hasResult) {
       return getCachedResult();
     }
     long remainingDeadline =
         TimeUnit.MILLISECONDS.convert(timeout, unit)
             - (System.currentTimeMillis() - tryLockStart);
     try {
       K value;
       try {
         value = parent.get(remainingDeadline, TimeUnit.MILLISECONDS);
       } catch (ExecutionException ex) {
         return handleParentException(ex.getCause());
       }
       return wrapAndCache(value);
     } catch (InterruptedException ex) {
       throw ex;
     } catch (TimeoutException ex) {
       throw ex;
     } catch (Throwable ex) {
       throw setExceptionResult(convertException(ex));
     }
   } finally {
     lock.unlock();
   }
 }
Пример #8
0
 public boolean lock() {
   try {
     return mLock.tryLock(1000L, TimeUnit.MILLISECONDS);
   } catch (InterruptedException e) {
     return false;
   }
 }
 /**
  * Tries to call the given consistent operation while holding the given lock.
  *
  * <p>If this is the first execution of this method on the call stack of the current thread, then
  * the lock gets acquired using {@link Lock#lock()}. Once the lock has been acquired the operation
  * gets called. If this fails for some reason and the thrown exception chain contains a {@link
  * FsNeedsLockRetryException}, then the lock gets temporarily released and the current thread gets
  * paused for a small random time interval before this procedure starts over again. Otherwise, the
  * exception chain gets just passed on to the caller.
  *
  * <p>If this is <em>not</em> the first execution of this method on the call stack of the current
  * thread, then the lock gets acquired using {@link Lock#tryLock()} instead. If this fails, an
  * {@code FsNeedsLockRetryException} gets created and passed to the given exception handler for
  * mapping before finally throwing the resulting exception by executing {@code throw
  * handler.fail(new FsNeedsLockRetryException())}. Once the lock has been acquired the operation
  * gets called. If this fails for some reason then the exception chain gets just passed on to the
  * caller.
  *
  * <p>This algorithm prevents dead locks effectively by temporarily unwinding the stack and
  * releasing all locks for a small random time interval. Note that this requires some minimal
  * cooperation by the operation: Whenever it throws an exception, it MUST leave its resources in a
  * consistent state so that it can get retried again! Mind that this is standard requirement for
  * any {@link FsController}.
  *
  * @param  <T> The return type of the operation.
  * @param operation The atomic operation.
  * @param lock The lock to hold while calling the operation.
  * @return The result of the operation.
  * @throws IOException As thrown by the operation.
  * @throws FsNeedsLockRetryException See above.
  */
 private <T> T locked(final Operation<T> operation, final Lock lock) throws IOException {
   final Account account = accounts.get();
   if (0 < account.lockCount) {
     if (!lock.tryLock()) throw FsNeedsLockRetryException.get();
     account.lockCount++;
     try {
       return operation.call();
     } finally {
       account.lockCount--;
       lock.unlock();
     }
   } else {
     try {
       while (true) {
         try {
           lock.lock();
           account.lockCount++;
           try {
             return operation.call();
           } finally {
             account.lockCount--;
             lock.unlock();
           }
         } catch (FsNeedsLockRetryException ex) {
           account.pause();
         }
       }
     } finally {
       accounts.remove();
     }
   }
 }
  /*
   * checkUpdateState
   *
   * checkUpdateState will only allow one thread to update the state at one time.
   * Those threads who want to access the state will wait on a lock until the updating thread finishes
   * the attempt to update.
   *
   * In the event there's an exception when a thread updates the state, there is no side-effect on the state itself
   * or on the trackerclients. Other threads will attempt the update the state as if the previous attempt did not happen.
   *
   * @param clusterGenerationId
   * @param trackerClients
   */
  private void checkUpdateState(long clusterGenerationId, List<TrackerClient> trackerClients) {
    DegraderLoadBalancerStrategyConfig config = getConfig();

    if (!_state.isInitialized()) {
      // threads attempt to access the state would block here if state is not initialized
      _lock.lock();
      try {
        if (!_state.isInitialized()) {
          debug(_log, "initializing load balancer strategy state");
          updateState(clusterGenerationId, trackerClients, config);
          if (!getState().isInitialized()) {
            _log.error("Failed to initialize state");
          }
        }
      } finally {
        _lock.unlock();
      }
    } else if (shouldUpdate(clusterGenerationId, _state, config, _updateEnabled)) {
      // threads attempt to update the state would return immediately if some thread is already in
      // the updating process
      if (_lock.tryLock()) {
        try {
          if (shouldUpdate(clusterGenerationId, _state, config, _updateEnabled)) {
            debug(_log, "updating for cluster generation id: ", clusterGenerationId);
            debug(_log, "old state was: ", _state);
            updateState(clusterGenerationId, trackerClients, config);
          }
        } finally {
          _lock.unlock();
        }
      }
    }
  }
 /**
  * Attempt to acquire lock.
  *
  * @param msecs the number of milleseconds to wait. An argument less than or equal to zero means
  *     not to wait at all.
  * @return <code>true</code> if acquired, <code>false</code> othwerwise.
  */
 public boolean acquire(long msecs) {
   try {
     return lock.tryLock(msecs, TimeUnit.MILLISECONDS);
   } catch (InterruptedException ie) {
     return false;
   }
 }
Пример #12
0
  /**
   * Return the locked document lock. Must be called before beforeUpdate().
   *
   * @param parameters incoming Ajax request
   * @return the document lock, already locked
   */
  public Lock acquireDocumentLock(RequestParameters parameters) {
    assert parameters.getUUID() != null;

    // Check that the session is associated with the requested UUID. This enforces the rule that an
    // incoming request
    // for a given UUID must belong to the same session that created the document. If the session
    // expires, the
    // key goes away as well, and the key won't be present. If we don't do this check, the XForms
    // server might
    // handle requests for a given UUID within a separate session, therefore providing access to
    // other sessions,
    // which is not desirable. Further, we now have a lock stored in the session.
    final Lock lock = getDocumentLock(parameters.getUUID());
    if (lock == null)
      throw new OXFException("Document session has expired. Unable to process incoming request.");

    // Lock document for at most the max retry delay plus an increment
    try {
      final boolean acquired =
          lock.tryLock(
              XFormsProperties.getAjaxTimeout() + XFormsProperties.getRetryDelayIncrement(),
              TimeUnit.MILLISECONDS);
      if (acquired) return lock;
      else return null;
    } catch (InterruptedException e) {
      throw new OXFException(e);
    }
  }
Пример #13
0
  @Test
  @Category(ProblematicTest.class) // TODO
  public void testLockInterruption() throws InterruptedException {
    Config config = new Config();
    config.setProperty(GroupProperties.PROP_OPERATION_CALL_TIMEOUT_MILLIS, "5000");
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1);
    final HazelcastInstance hz = nodeFactory.newHazelcastInstance(config);

    final Lock lock = hz.getLock("testLockInterruption2");
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  lock.tryLock(60, TimeUnit.SECONDS);
                } catch (InterruptedException ignored) {
                  latch.countDown();
                }
              }
            });
    lock.lock();
    t.start();
    Thread.sleep(2000);
    t.interrupt();
    assertTrue("tryLock() is not interrupted!", latch.await(30, TimeUnit.SECONDS));
    lock.unlock();
    assertTrue("Could not acquire lock!", lock.tryLock());
  }
Пример #14
0
  /**
   * If the coordinator of the lock locks the lock and then send a message, the receiver will wait
   * for ever in tryLock. However, castMessage will return after a while because of the default
   * settings of RequestOptions.SYNC().
   */
  public void testCoordSendFirst() throws Exception {
    System.out.println("Running testCoordSendFirst");

    // ===========================================================================
    if (lock_a.tryLock()) {
      try {
        System.out.println("A aquired the lock, about to send message to B");
        String rsp =
            disp_a.sendMessage(
                new Message(b.getAddress(), "bla"), RequestOptions.SYNC().setTimeout(60000));
        if (rsp == null) {
          System.err.println("ERROR: didn't return correctly");
          Assert.fail("Didn't return correctly");
        } else System.out.println("Returned: " + rsp);

      } finally {
        lock_a.unlock();
      }
    } else {
      Assert.fail("The lock was already locked");
      System.out.println("A failed to aquire the lock");
    }
    // ===========================================================================

    System.out.println();
  }
  private Lock aquireLock(
      boolean read, final Duration accessTimeout, final Instance instance, final Method runMethod) {
    final Lock lock;
    if (read) {
      lock = instance.lock.readLock();
    } else {
      lock = instance.lock.writeLock();
    }

    boolean lockAcquired;
    if (accessTimeout == null || accessTimeout.getTime() < 0) {
      // wait indefinitely for a lock
      lock.lock();
      lockAcquired = true;
    } else if (accessTimeout.getTime() == 0) {
      // concurrent calls are not allowed, lock only once
      lockAcquired = lock.tryLock();
    } else {
      // try to get a lock within the specified period.
      try {
        lockAcquired = lock.tryLock(accessTimeout.getTime(), accessTimeout.getUnit());
      } catch (InterruptedException e) {
        throw (ConcurrentAccessTimeoutException)
            new ConcurrentAccessTimeoutException(
                    "Unable to get "
                        + (read ? "read" : "write")
                        + " lock within specified time on '"
                        + runMethod.getName()
                        + "' method for: "
                        + instance.bean.getClass().getName())
                .initCause(e);
      }
    }

    // Did we acquire the lock to the current execution?
    if (!lockAcquired) {
      throw new ConcurrentAccessTimeoutException(
          "Unable to get "
              + (read ? "read" : "write")
              + " lock on '"
              + runMethod.getName()
              + "' method for: "
              + instance.bean.getClass().getName());
    }

    return lock;
  }
Пример #16
0
  @Override
  public void onLookEdit(View view) {
    if (!viewSwitchLock.tryLock()) {
      return;
    }

    handleEditLook(view);
  }
Пример #17
0
 /**
  * Try to acquire the given lock, adding it to a list of held locks for cleanup on thread
  * termination if it is acquired. Return immediately if the lock cannot be acquired.
  *
  * @param lock the lock to acquire, released on thread termination
  */
 public boolean tryLock(Lock lock) {
   assert Thread.currentThread() == getNativeThread();
   boolean locked = lock.tryLock();
   if (locked) {
     heldLocks.add(lock);
   }
   return locked;
 }
Пример #18
0
 @Override
 public boolean tryLock(String name, long timeout, TimeUnit unit) {
   Lock lock = getLock(name);
   try {
     return lock.tryLock(timeout, unit);
   } catch (InterruptedException e) {
     return false;
   }
 }
Пример #19
0
  @Override
  public void handleAddButton() {
    if (!viewSwitchLock.tryLock()) {
      return;
    }

    NewLookDialog dialog = new NewLookDialog();
    dialog.showDialog(getActivity().getSupportFragmentManager(), this);
  }
Пример #20
0
 private void acquireLock(Lock lock) {
   try {
     if (!lock.tryLock(asyncStoreConfig.getFlushLockTimeout(), TimeUnit.MILLISECONDS))
       throw new CacheException("Unable to acquire lock on update map");
   } catch (InterruptedException ie) {
     // restore interrupted status
     Thread.currentThread().interrupt();
   }
 }
Пример #21
0
 public boolean trySendOnSharedLine(String message, long timeout, TimeUnit unit)
     throws InterruptedException {
   long nanosToLock = unit.toNanos(timeout) - estimatedNanosToSend(message);
   if (!lock.tryLock(nanosToLock, NANOSECONDS)) return false;
   try {
     return sendOnSharedLine(message);
   } finally {
     lock.unlock();
   }
 }
 private void obtainLock(Lock lock, String source) {
   try {
     if (!lock.tryLock(getLockTimeout(), TimeUnit.MILLISECONDS)) {
       dumpThreads();
       throw new IllegalStateException("Could not obtain lock");
     }
   } catch (InterruptedException e) {
     try {
       if (!lock.tryLock(getLockTimeout(), TimeUnit.MILLISECONDS)) {
         dumpThreads();
         throw new IllegalStateException("Could not obtain lock");
       }
     } catch (InterruptedException e1) {
       Thread.currentThread().interrupt();
       // TODO is there a better exception to throw?
       throw new IllegalStateException("Interrupted twice: Could not obtain lock");
     }
     Thread.currentThread().interrupt();
   }
 }
Пример #23
0
  public boolean tryAcquireSharedLock(T value, long timeout) throws InterruptedException {
    if (useSpinLock) throw new IllegalStateException("Spin lock does not support try lock mode");

    final int index;
    if (value == null) index = 0;
    else index = index(value.hashCode());

    final ReadWriteLock rwLock = locks[index];

    final Lock lock = rwLock.readLock();
    return lock.tryLock(timeout, TimeUnit.MILLISECONDS);
  }
Пример #24
0
 public static void main(String args[]) throws InterruptedException, KeeperException {
   ZooQueueLock lock = new ZooQueueLock("/lock", true);
   DistributedReadWriteLock rlocker = new DistributedReadWriteLock(lock, "reader".getBytes(UTF_8));
   DistributedReadWriteLock wlocker =
       new DistributedReadWriteLock(lock, "wlocker".getBytes(UTF_8));
   final Lock readLock = rlocker.readLock();
   readLock.lock();
   final Lock readLock2 = rlocker.readLock();
   readLock2.lock();
   final Lock writeLock = wlocker.writeLock();
   if (writeLock.tryLock(100, TimeUnit.MILLISECONDS))
     throw new RuntimeException("Write lock achieved during read lock!");
   readLock.unlock();
   readLock2.unlock();
   writeLock.lock();
   if (readLock.tryLock(100, TimeUnit.MILLISECONDS))
     throw new RuntimeException("Read lock achieved during write lock!");
   final Lock writeLock2 = DistributedReadWriteLock.recoverLock(lock, "wlocker".getBytes(UTF_8));
   writeLock2.unlock();
   readLock.lock();
   System.out.println("success");
 }
 public String handleCommand(final String command) throws InterruptedException {
   if ("exit".equals(command) || "quit".equals(command)) {
     return "'" + command + "' is not allowed!";
   }
   if (lock.tryLock(1, TimeUnit.SECONDS)) {
     try {
       return doHandleCommand(command);
     } finally {
       lock.unlock();
     }
   }
   return "'" + command + "' execution is timed out!";
 }
 public int deleteOrphanedPrivateFiles() throws Exception {
   if (deleteOrphanedPrivateFilesLock.tryLock()) {
     try {
       isRunningDeleteOrphanedPrivateFiles = true;
       return internalDeleteOrphanedPrivateFiles();
     } finally {
       deleteOrphanedPrivateFilesLock.unlock();
       isRunningDeleteOrphanedPrivateFiles = false;
     }
   } else {
     log.info("DeleteOrphanedPrivateFiles is already running!");
     return -1;
   }
 }
Пример #27
0
  /**
   * {@inheritDoc}
   *
   * @see net.sf.hajdbc.distributed.Command#execute(java.lang.Object)
   */
  @Override
  public Boolean execute(LockCommandContext context) {
    Lock lock = context.getLock(this.descriptor);

    boolean locked = lock.tryLock();

    if (locked) {
      Map<LockDescriptor, Lock> lockMap = context.getRemoteLocks(this.descriptor);

      synchronized (lockMap) {
        lockMap.put(this.descriptor, lock);
      }
    }

    return locked;
  }
 /**
  * tryLock 方法
  *
  * <p>如果该锁没有被另一个线程保持,并且立即返回 true 值。
  *
  * <p>如果锁被另一个线程保持,则此方法将立即返回 false 值。
  */
 public void tryLock() {
   while (true) {
     if (lock.tryLock()) {
       try {
         System.out.println(Thread.currentThread().getName() + " begin");
         // do something
         Thread.sleep(200);
         System.out.println(Thread.currentThread().getName() + " eng");
       } catch (InterruptedException e) {
         e.printStackTrace();
       } finally {
         lock.unlock();
       }
     }
   }
 }
Пример #29
0
  public void someMethod() {
    if (!lock.tryLock()) {
      try {
        ifLockIsBusy();
      } finally {
        lock.unlock();
      }

    } else {
      try {
        ifLockIsFree();
      } finally {
        lock.unlock();
      }
    }
    // implement logic here, use the lock field
  }
Пример #30
0
 @Override
 public Component findComponentAt(int x, int y) {
   final Component c = super.findComponentAt(x, y);
   if (c == null) {
     return null;
   }
   final AWTEvent currentEvent = EventQueue.getCurrentEvent();
   if (controller != Controller.getCurrentController()
       && currentEvent instanceof MouseEvent
       && currentEvent.getID() == MouseEvent.MOUSE_MOVED) {
     if (appletLock.tryLock()) {
       Controller.setCurrentController(controller);
       appletLock.unlock();
     }
   }
   return c;
 }