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

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

Introduction

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

Prototype

public void lockInterruptibly() throws InterruptedException 

Source Link

Document

Acquires the lock unless the current thread is Thread#interrupt interrupted .

Usage

From source file:com.chicm.cmraft.util.CappedPriorityBlockingQueue.java

@Override
public boolean offer(E e) {
    boolean ret = false;
    final ReentrantLock putLock = this.putLock;
    try {//w  ww .  j a  v  a 2  s  .co m
        putLock.lockInterruptibly();
        while (size() >= this.maxCapacity) {
            LOG.debug("Thread:" + Thread.currentThread().getName() + ": queue is full, waiting...");
            notFull.await();
            LOG.debug("Thread:" + Thread.currentThread().getName() + ": waiting done");
        }

        ret = super.offer(e);
        if (size() < this.maxCapacity)
            notFull.signal();
    } catch (InterruptedException ex) {
        LOG.error("InterruptedException", ex);
        return false;
    } finally {
        putLock.unlock();
    }
    return ret;
}

From source file:com.googlecode.msidor.springframework.integration.channel.ConcurentOrderedMultiQueueChannel.java

/**
 * Unlock the execution ID.//from   w w w.  java2s.  co  m
 * This method lock the object to perform manipulation on locks collection and to notify dormant consumer threads that there are potential messages to check.
 * 
 * @param message to unlock
 */
public void unlockExecutionId(Message<?> message) {
    final ReentrantLock lock = this.objectLock;

    try {
        lock.lockInterruptibly();

        Object executionId = getExecutionIdFromMessage(message);

        log.trace("Unlocking execution " + executionId);

        if (executionId != null) {
            executionsLocks.remove(executionId);
        }
    } catch (InterruptedException e) {
        log.trace("Lock interrupted by other thread");
    } finally {
        newMessagesToCheck.signal();
        lock.unlock();
    }
}

From source file:com.googlecode.msidor.springframework.integration.channel.ConcurentOrderedMultiQueueChannel.java

/**
 * Handles the demands for messages/*from w  ww  . j av  a 2  s .  co m*/
 * 
 * @param timeout [ms] - time for which the thread will stay blocked if there are no eligible messages to process.
 * @return message to process
 */
@Override
protected Message<?> doReceive(long timeout) {
    log.trace("Asking for message to process");

    //the message to be returned
    Message<?> messageToReturn = null;

    int c = -1;
    long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);

    final ReentrantLock lock = this.objectLock;
    final AtomicInteger count = this.count;

    try {
        //take the lock
        lock.lockInterruptibly();

        while (messageToReturn == null) {
            //try to get eligible message
            messageToReturn = findEligibleMessage();

            //if message was found
            if (messageToReturn != null) {
                //decrement the global messages counter
                c = count.getAndDecrement();

                //if there are some messages wake up the next consumer thread to check if there is new eligible message
                if (c > 0)
                    newMessagesToCheck.signal();
            } else {
                //go to sleep waiting for new eligible message

                if (timeout <= 0) {
                    newMessagesToCheck.await();
                } else {
                    nanos = newMessagesToCheck.awaitNanos(nanos);

                    if (nanos <= 0)
                        return null;
                }
            }
        }
    } catch (InterruptedException e) {
        log.trace("Lock interrupted by other thread");
    } finally {
        //if message was found, wake the producer thread to notify it that there is a free space to insert new message 
        if (messageToReturn != null)
            notFull.signal();

        lock.unlock();
    }

    log.trace("Rreceiving message " + messageToReturn);

    return messageToReturn;
}

From source file:com.googlecode.msidor.springframework.integration.channel.ConcurentOrderedMultiQueueChannel.java

/**
 * Adds message to the queue./*from w  w  w .jav  a 2  s  . com*/
 * This method blocks if there is no space.
 * @param message to be added
 * @param timeout after which the method awakes from waiting for free space (0 for no timeout)
 * @return true if message was successfully added to queue
 */
@Override
protected boolean doSend(Message<?> message, long timeout) {
    Assert.notNull(message, "'message' must not be null");

    log.trace("Sending message " + message);

    long nanos = TimeUnit.MILLISECONDS.toNanos(timeout);
    int c = -1;
    final ReentrantLock lock = this.objectLock;
    final AtomicInteger count = this.count;
    try {
        //lock the object exclusively
        lock.lockInterruptibly();

        while (count.get() == totalCapacity) {
            //if timeout was set and has elapsed
            if (nanos <= 0 && timeout > 0)
                return false;

            //wait for notification when any message has been handled
            if (timeout > 0) {
                nanos = notFull.awaitNanos(nanos);
            } else {
                notFull.await();
            }
        }

        //add message to the queue
        addMessage(message);

        c = count.getAndIncrement();

        //if there is still some space notify any other potentially dormant producer thread
        if (c + 1 < totalCapacity)
            notFull.signal();

    } catch (InterruptedException e) {
        log.trace("Lock interrupted by other thread");
    } finally {
        //notify potentially dormant consumer thread that there is a message to handle 
        newMessagesToCheck.signal();
        lock.unlock();
    }

    return true;
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

/**
 * Retrieves and removes the head of this queue, waiting if necessary until
 * an element with an expired delay is available on this queue.
 *
 * @return the head of this queue/*from   w w  w .  j a  v  a2 s.co  m*/
 * @throws InterruptedException
 *             {@inheritDoc}
 */
public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    long t = now();
    TenantQueue.Item item = null;
    try {
        for (;;) {
            TenantQueue q = nextQueue(t);
            if (q == null)
                available.await();
            else {
                long delay = q.next - t;
                if (delay <= 0) {
                    item = q.poll(t);
                    return item == null ? null : item.element;
                } else if (leader != null)
                    available.await();
                else {
                    Thread thisThread = Thread.currentThread();
                    leader = thisThread;
                    try {
                        available.awaitNanos(delay);
                    } finally {
                        if (leader == thisThread)
                            leader = null;
                    }
                }
            }
            t = System.nanoTime();
        }
    } finally {
        if (leader == null && hasNext())
            available.signal();
        lock.unlock();
        done(item, t);
    }
}

From source file:edu.brown.cs.systems.retro.throttling.throttlingqueues.ThrottlingLockingQueue.java

/**
 * Retrieves and removes the head of this queue, waiting if necessary until
 * an element with an expired delay is available on this queue, or the
 * specified wait time expires./*from  ww w .  j  a  va2s.com*/
 *
 * @return the head of this queue, or <tt>null</tt> if the specified waiting
 *         time elapses before an element with an expired delay becomes
 *         available
 * @throws InterruptedException
 *             {@inheritDoc}
 */
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    long t = now();
    TenantQueue.Item item = null;
    try {
        for (;;) {
            TenantQueue q = nextQueue(t);
            if (q == null) {
                if (nanos <= 0)
                    return null;
                else
                    nanos = available.awaitNanos(nanos);
            } else {
                long delay = q.next - t;
                if (delay <= 0) {
                    item = q.poll(t);
                    return item == null ? null : item.element;
                }
                if (nanos <= 0)
                    return null;
                if (nanos < delay || leader != null)
                    nanos = available.awaitNanos(nanos);
                else {
                    Thread thisThread = Thread.currentThread();
                    leader = thisThread;
                    try {
                        long timeLeft = available.awaitNanos(delay);
                        nanos -= delay - timeLeft;
                    } finally {
                        if (leader == thisThread)
                            leader = null;
                    }
                }
            }
            t = System.nanoTime();
        }
    } finally {
        if (leader == null && hasNext())
            available.signal();
        lock.unlock();
        done(item, t);
    }
}

From source file:org.commonjava.maven.galley.cache.infinispan.FastLocalCacheProvider.java

private <K> K tryLockAnd(ConcreteResource resource, long timeout, TimeUnit unit, TransferLockTask<K> task)
        throws IOException {
    ReentrantLock lock = getTransferLock(resource);
    boolean locked = false;
    try {/*w w  w .  ja  v a2  s  .  c om*/
        if (timeout > 0) {
            locked = lock.tryLock(timeout, unit);
            if (locked) {
                return task.execute(resource);
            } else {
                throw new IOException(
                        String.format("Did not get lock for resource %s in %d %s, timeout happened.", resource,
                                timeout, unit.toString()));
            }
        } else {
            lock.lockInterruptibly();
            return task.execute(resource);
        }

    } catch (InterruptedException e) {
        logger.warn("Interrupted for the transfer lock with resource: {}", resource);
        return null;
    } finally {
        if (timeout <= 0 || locked) {
            lock.unlock();
        }
    }
}