Example usage for java.util.concurrent.locks ReentrantLock isLocked

List of usage examples for java.util.concurrent.locks ReentrantLock isLocked

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock isLocked.

Prototype

public boolean isLocked() 

Source Link

Document

Queries if this lock is held by any thread.

Usage

From source file:RefinableHashSet.java

/**
 * Ensure that no thread is currently locking the set.
 *//*from  w w  w. j  a  v  a 2 s  .c  o m*/
protected void quiesce() {
    for (ReentrantLock lock : locks) {
        while (lock.isLocked()) {
        } // spin
    }
}

From source file:org.ut.biolab.medsavant.server.db.LockController.java

/**
 * Check if the project is locked//  w w w  .  j  a  v a  2s.c  om
 *
 * @param database The database containing the project to unlock.
 * @param projectID The project ID to check.
 * @return Whether the project is locked.
 */
public boolean isLocked(String database, int projectID) {
    ReentrantLock l = locks.get(new Key(database, projectID));

    // l will be null if no one has requested a lock for the project before
    if (l == null) {
        return false;
    }

    return l.isLocked();
}

From source file:org.ut.biolab.medsavant.server.db.LockController.java

/**
 * Release the lock. If force is false, only the thread which requested the
 * lock may unlock. However, in the case where that thread no longer exists,
 * it is necessary to force the unlock.//  w w  w  .  jav a  2s.  co  m
 *
 * @param database The database containing the project to unlock.
 * @param projectID The project ID to unlock.
 * @param force Whether to force the unlock.
 * @throws org.ut.biolab.medsavant.shared.model.LockException
 */
public synchronized void releaseLock(String database, int projectID, boolean force) throws LockException {

    LOG.info("Server unlock requested");

    Key k = new Key(database, projectID);
    ReentrantLock lock = locks.get(k);

    // no lock exists for this project
    if (lock == null) {
        throw new LockException("No lock exists");
    }

    if (force) {
        while (lock.isLocked()) {
            lock.unlock();
        }
        LOG.info(String.format("Server forcibly unlocked - hold count %d", lock.getHoldCount()));

        // unlock it, or decrement the hold count
    } else if (lock.isHeldByCurrentThread()) {
        lock.unlock();
        LOG.info(String.format("Server unlocked - hold count %d", lock.getHoldCount()));
        // not allowed to lock
    } else {
        throw new LockException("Database could not be unlocked");
    }
}

From source file:org.ut.biolab.medsavant.server.db.LockController.java

/**
 * Obtain a lock. If another thread already owns the lock, an exception will
 * be thrown.//from w  w  w .  ja  v  a  2  s .  c  om
 *
 * @param database The database with the project to be unlocked.
 * @param projectID The project ID to lock
 * @throws LockException
 */
public synchronized void requestLock(String database, int projectID) throws LockException {
    LOG.info("Server lock requested");
    Key key = new Key(database, projectID);
    ReentrantLock lock = locks.get(key);

    // create the lock if one doesn't exist for the project
    if (lock == null) {
        lock = new ReentrantLock();
        locks.put(key, lock);
    }

    // lock it down 
    // (if this thread owns the lock, call lock again which will increase the hold count)
    if (!lock.isLocked() || lock.isHeldByCurrentThread()) {
        lock.lock();
        LOG.info(String.format("Server locked - hold count %d", lock.getHoldCount()));
    } else {
        throw new LockException("Database is locked for changes");
    }
}

From source file:io.tilt.minka.business.impl.SemaphoreImpl.java

private Permission checkState(final Action action) {
    if (action.getScope() == Scope.LOCAL) {
        final ReentrantLock lock = g(action);
        if (lock.isHeldByCurrentThread()) {
            logger.error("{}: {} lock already acquired by YOU ! CHECK YOUR CODE !", getClass().getSimpleName(),
                    action);//from w w  w .j  a  v a 2 s  .co m
            return DENIED;
            //throw new RuntimeException("Come on check your code consistency pal !");
        } else if (lock.isLocked()) {
            logger.error("{}: {} lock already acquired by {} thread ! and holds: {} more",
                    getClass().getSimpleName(), action, lock.isHeldByCurrentThread() ? "current" : "sibling",
                    lock.getQueueLength());
            return DENIED;
        }
    } else if (action.getScope() == Scope.GLOBAL) {
        // TODO
    }

    // in the case of not being slave to those master to me or any (got that?)
    // i simply let them acquire, otherwise behead it !
    for (final Entry<Action, Rule> entry : rules.entrySet()) {
        final List<Action> related = entry.getValue().getRelated(PARENT);
        if (!related.isEmpty()) {
            if (isLocked(entry.getKey()) && (related.contains(ANY) || related.contains(action))) {
                if (!rules.get(action).getRelated(CHILD).contains(entry.getKey())) {
                    logger.warn(
                            "{}: {} Cannot be acquired because not Child of previously acquired Parent lock: {}",
                            getClass().getSimpleName(), action, entry.getKey());
                    return DENIED;
                }
            }
        }
    }

    return null;
}

From source file:ir.rasen.charsoo.controller.image_loader.core.LoadAndDisplayImageTask.java

@Override
public void run() {
    if (waitIfPaused())
        return;//from w  ww  .  j a va  2 s.  co  m
    if (delayIfNeed())
        return;

    ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;
    L.d(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey);
    if (loadFromUriLock.isLocked()) {
        L.d(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey);
    }

    loadFromUriLock.lock();
    Bitmap bmp;
    try {
        checkTaskNotActual();

        bmp = configuration.memoryCache.get(memoryCacheKey);
        if (bmp == null || bmp.isRecycled()) {
            bmp = tryLoadBitmap();
            if (bmp == null)
                return; // listener callback already was fired

            checkTaskNotActual();
            checkTaskInterrupted();

            if (options.shouldPreProcess()) {
                L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey);
                bmp = options.getPreProcessor().process(bmp);
                if (bmp == null) {
                    L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);
                }
            }

            if (bmp != null && options.isCacheInMemory()) {
                L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);
                configuration.memoryCache.put(memoryCacheKey, bmp);
            }
        } else {
            loadedFrom = LoadedFrom.MEMORY_CACHE;
            L.d(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey);
        }

        if (bmp != null && options.shouldPostProcess()) {
            L.d(LOG_POSTPROCESS_IMAGE, memoryCacheKey);
            bmp = options.getPostProcessor().process(bmp);
            if (bmp == null) {
                L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey);
            }
        }
        checkTaskNotActual();
        checkTaskInterrupted();
    } catch (TaskCancelledException e) {
        fireCancelEvent();
        return;
    } finally {
        loadFromUriLock.unlock();
    }

    DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
    runTask(displayBitmapTask, syncLoading, handler, engine);
}

From source file:net.ymate.module.oauth.client.impl.DefaultOAuthClientTokenStorageAdapter.java

@Override
public OAuthAccessToken loadAccessToken(OAuthAccount account) {
    OAuthAccessToken _accessToken = __TOKEN_CACHES.get(account.getId());
    if (_accessToken == null || _accessToken.isExpired()) {
        ReentrantLock _locker = ReentrantLockHelper.DEFAULT.getLocker(account.getId().concat("_token"));
        _locker.lock();/*from  w  w w.  ja v  a  2  s  .c  om*/
        try {
            _accessToken = __doGetAccessToken(account.getId());
            if (_accessToken == null || _accessToken.isExpired()) {
                _accessToken = __doGetAccessToken(account);
            }
        } catch (Exception e) {
            try {
                _accessToken = __doGetAccessToken(account.getId());
                if (_accessToken == null || _accessToken.isExpired()) {
                    _accessToken = __doGetAccessToken(account);
                }
            } catch (Exception ex) {
                _LOG.warn("Exception when loading access_token: ", RuntimeUtils.unwrapThrow(ex));
            }
        } finally {
            if (_locker.isLocked()) {
                _locker.unlock();
            }
        }
    }
    return _accessToken;
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Determine if this connection is within a transaction
 * //from www . jav  a 2  s .c om
 * @param connection
 *            connection of which to determine transaction status
 * @return true if connection is within transaction
 */
public boolean isInTransaction(Connection connection) {
    ReentrantLock lock = connectionLocks.get(connection);
    if (lock != null) {
        return lock.isLocked();
    }
    return false;
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Begin database transaction//from www  .j a  v  a  2  s  .  c om
 * 
 * Note:Database already in transaction
 * 
 * @param connection
 *            {@link Connection} to underlying database
 * @param needsWrite
 *            if true, tables will be locked if needed
 * @param needsTransaction
 *            TODO
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#ALREADY_IN_RDB_TRANSACTION} if this connection is already with a transaction
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_START_RDB_TRANSACTION} if there was a problem setting autoCommit to false
 */
public void begin(Connection connection, boolean needsWrite, boolean needsTransaction) throws AnzoException {
    long start = 0;
    if (stats.isEnabled()) {
        start = System.currentTimeMillis();
        stats.getBeginUse().increment();
    }
    try {
        ReentrantLock lock = connectionLocks.get(connection);
        if (lock == null) {
            lock = new ReentrantLock();
            connectionLocks.put(connection, lock);
        }
        if (lock.isLocked()) {
            throw new AnzoException(ExceptionConstants.RDB.ALREADY_IN_RDB_TRANSACTION);
        }
        lock.lock();
        if (lock.getHoldCount() == 1 && needsTransaction) {
            try {
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                lock.unlock();
                log.error(LogUtils.RDB_MARKER, "Error starting jdbc transaction", e);
                throw new AnzoRuntimeException(ExceptionConstants.RDB.FAILED_START_RDB_TRANSACTION, e);
            }
            try {
                lockTable(connection, needsWrite);
            } catch (AnzoException e) {
                try {
                    connection.setAutoCommit(false);
                } catch (SQLException sqle) {
                    log.error(LogUtils.RDB_MARKER, "Error aborting jdbc transaction", sqle);
                }
                lock.unlock();
                throw e;
            }

        }
    } finally {
        if (stats.isEnabled()) {
            stats.getBeginDuration().addTime((System.currentTimeMillis() - start));
        }
    }
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Commit database transaction/*from  ww w .  j av  a 2s  .co  m*/
 * 
 * Note:Database already in transaction
 * 
 * @param connection
 *            {@link Connection} to underlying database
 * @param needsWrite
 *            if true, tables will be locked if needed
 * @param needsTransaction
 *            TODO
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#NOT_IN_RDB_TRANSACTION} if connection isn't in a transaction
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#DIDNT_START_RDB_TRANSACTION} if this thread didn't start the transaction
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_COMMIT_RDB_TRANSACTION} if there was a problem committing the connection
 */
public void commit(Connection connection, boolean needsWrite, boolean needsTransaction) throws AnzoException {
    long start = 0;
    if (stats.isEnabled()) {
        start = System.currentTimeMillis();
        stats.getCommitUse().increment();
    }
    try {
        ReentrantLock lock = connectionLocks.get(connection);
        if (lock == null) {
            lock = new ReentrantLock();
            connectionLocks.put(connection, lock);
        }
        if (lock.isLocked()) {
            if (lock.isHeldByCurrentThread()) {
                try {
                    if (needsTransaction) {
                        ArrayList<AnzoException> exceptions = null;
                        try {
                            connection.commit();
                            connection.setAutoCommit(true);
                        } catch (SQLException e) {
                            log.error(LogUtils.RDB_MARKER, "Error commmiting jdbc transaction", e);
                            exceptions = new ArrayList<AnzoException>();
                            exceptions.add(
                                    new AnzoException(ExceptionConstants.RDB.FAILED_COMMIT_RDB_TRANSACTION, e));
                        }
                        try {
                            unlockTable(connection, needsWrite);
                        } catch (AnzoException ae) {
                            log.error(LogUtils.RDB_MARKER, "Error unlocking tables", ae);
                            if (exceptions == null) {
                                exceptions = new ArrayList<AnzoException>();
                            }
                            exceptions.add(ae);
                        }
                        if (exceptions != null && exceptions.size() > 0) {
                            throw new CompoundAnzoException(exceptions,
                                    ExceptionConstants.RDB.FAILED_COMMIT_RDB_TRANSACTION);
                        }
                    }
                } finally {
                    lock.unlock();
                    nodeLayout.clearUncommittedCache();
                }
            } else {
                throw new AnzoException(ExceptionConstants.RDB.DIDNT_START_RDB_TRANSACTION);
            }
        } else {
            throw new AnzoException(ExceptionConstants.RDB.NOT_IN_RDB_TRANSACTION);
        }
    } finally {
        if (stats.isEnabled()) {
            stats.getCommitDuration().addTime((System.currentTimeMillis() - start));
        }
    }
}