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

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

Introduction

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

Prototype

public boolean isHeldByCurrentThread() 

Source Link

Document

Queries if this lock is held by the current thread.

Usage

From source file:Main.java

public static void requireLock(ReentrantLock lock) {
    if (!lock.isHeldByCurrentThread()) {
        throw new RuntimeException(
                "Lock is not held by current thread: thread-name = " + Thread.currentThread().getName());
    }//from  w w  w  .  j  ava2 s. co  m
}

From source file:Main.java

public static void assertLockIsNotHeld(ReentrantLock lock) {
    if (lock.isHeldByCurrentThread()) {
        throw new RuntimeException("Assert: lock is held by current thread but shouldn't be");
    }/* w  w  w.ja va  2s  .  co m*/
}

From source file:Main.java

public static void assertLockIsHeld(ReentrantLock lock) {
    if (!lock.isHeldByCurrentThread()) {
        throw new RuntimeException("Assert: mandatory lock isn't held by current thread");
    }//from w ww. ja  v  a 2s .co m
}

From source file:Main.java

private static String getLockInfo(ReentrantLock lock) {
    String lockid = "Lock@" + Integer.toHexString(lock.hashCode());
    return "lock " + lockid + " held=" + lock.getHoldCount() + " isHeldMe=" + lock.isHeldByCurrentThread()
            + " hasQueueThreads=" + lock.hasQueuedThreads();
}

From source file:com.shigengyu.hyperion.cache.LocalWorkflowInstanceCache.java

@Override
public <T extends WorkflowInstance> void release(final T workflowInstance) {
    ReentrantLock lock = getLock(workflowInstance.getWorkflowInstanceId());
    if (!lock.isHeldByCurrentThread()) {
        throw new HyperionException(
                "Cannot release workflow instance [{}] as current thread does not own the lock",
                workflowInstance.getWorkflowInstanceId());
    }/*from w w w .j  a  va2 s  . c  o  m*/
    lock.unlock();
}

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  . java2 s.c  o 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:com.streamsets.datacollector.io.DataStore.java

@VisibleForTesting
void acquireLock() {
    LOG.trace("Acquiring lock for '{}'", file);
    ReentrantLock lock = null;
    synchronized (DataStore.class) {
        lock = FILE_LOCKS.get(file);//from w ww  . ja  v a  2 s.  co m
        if (lock == null) {
            lock = new ReentrantLock();
            FILE_LOCKS.put(file, lock);
        } else {
            Utils.checkState(!lock.isHeldByCurrentThread(),
                    Utils.format("The current thread already has a lock on '{}'", file));
        }
    }
    lock.lock();
    LOG.trace("Acquired lock for '{}'", file);
}

From source file:com.zimbra.cs.db.SQLite.java

private void releaseMboxDbLock(Integer mboxId) {
    if (mboxId != null) {
        ReentrantLock lock = null;
        lock = lockMap.get(mboxId);//from ww w.j av a  2  s. co  m
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
            ZimbraLog.dbconn.trace("unlocked mbox %d", mboxId);
        }
    }
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

private static void doChainFilter(final FilterChain chain, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {

    final HttpSession session = request.getSession();

    // fetch the user's deque
    final Deque<ServletRequest> deque = getUsersDeque(session);

    // lock to execute
    final ReentrantLock lock = (ReentrantLock) session.getAttribute(USER_REQUEST_LOCK);

    // deque has a time limit. start counting.
    long timeLeft = WAIT_TIME;

    try {/* w  w  w .  j  a  v  a 2  s  . com*/
        // attempt to join deque
        if (deque.offerFirst(request)) {
            timeLeft = tryLock(request, deque, lock, timeLeft);
        }

        if (lock.isHeldByCurrentThread()) {

            // waiting is over. and we can execute
            chain.doFilter(request, response);

        } else {
            // we failed to execute. return 409 response.
            if (response instanceof HttpServletResponse) {

                LOG.warn(" -- response 409 "
                        + (0 < timeLeft ? "(More then " + REQUEST_QUEUE_SIZE + " requests already in queue)"
                                : "(Timeout: Waited " + WAIT_TIME + " ms)"));

                response.sendError(HttpServletResponse.SC_CONFLICT);
            }
        }
    } finally {

        // take out of deque first
        deque.remove(request);

        // release the lock, waiting up the next request
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

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

/**
 * Abort database transaction/*from www.j ava 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#DIDNT_START_RDB_TRANSACTION} if this thread didn't start the transaction
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_ROLLBACK_RDB_TRANSACTION} if there was a problem rolling back the connection
 */
protected void abort(Connection connection, boolean needsWrite, boolean needsTransaction) throws AnzoException {
    long start = 0;
    if (stats.isEnabled()) {
        start = System.currentTimeMillis();
        stats.getAbortUse().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 {
                            if (!connection.isClosed()) {
                                try {
                                    connection.rollback();
                                    connection.setAutoCommit(true);
                                } catch (SQLException e) {
                                    log.error(LogUtils.RDB_MARKER, "Error rolling back transaction", e);
                                    exceptions = new ArrayList<AnzoException>();
                                    exceptions.add(new AnzoException(
                                            ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION, e));
                                }
                                try {
                                    unlockTable(connection, needsWrite);
                                } catch (AnzoException ae) {
                                    log.error(LogUtils.RDB_MARKER, "Error unlocking table", ae);
                                    if (exceptions == null) {
                                        exceptions = new ArrayList<AnzoException>();
                                    }
                                    exceptions.add(ae);
                                }
                            }
                        } catch (SQLException e) {
                            log.error(LogUtils.RDB_MARKER, "Error rollingback jdbc transaction", e);
                            exceptions = new ArrayList<AnzoException>();
                            exceptions.add(new AnzoException(
                                    ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION, e));
                        }

                        if (exceptions != null && exceptions.size() > 0) {
                            throw new CompoundAnzoException(exceptions,
                                    ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION);
                        }
                    }
                } finally {
                    lock.unlock();
                    nodeLayout.clearUncommittedCache();
                }
            } else {
                throw new AnzoException(ExceptionConstants.RDB.DIDNT_START_RDB_TRANSACTION);
            }
        }
    } finally {
        if (stats.isEnabled()) {
            stats.getAbortDuration().addTime((System.currentTimeMillis() - start));
        }
    }
}