Search in sources :

Example 11 with ReentrantLock

use of java.util.concurrent.locks.ReentrantLock in project Signal-Android by WhisperSystems.

the class LinkedBlockingDeque method clear.

/**
     * Atomically removes all of the elements from this deque.
     * The deque will be empty after this call returns.
     */
@Override
public void clear() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (Node<E> f = first; f != null; ) {
            f.item = null;
            Node<E> n = f.next;
            f.prev = null;
            f.next = null;
            f = n;
        }
        first = last = null;
        count = 0;
        notFull.signalAll();
    } finally {
        lock.unlock();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock)

Example 12 with ReentrantLock

use of java.util.concurrent.locks.ReentrantLock in project Signal-Android by WhisperSystems.

the class LinkedBlockingDeque method remainingCapacity.

/**
     * Returns the number of additional elements that this deque can ideally
     * (in the absence of memory or resource constraints) accept without
     * blocking. This is always equal to the initial capacity of this deque
     * less the current {@code size} of this deque.
     *
     * <p>Note that you <em>cannot</em> always tell if an attempt to insert
     * an element will succeed by inspecting {@code remainingCapacity}
     * because it may be the case that another thread is about to
     * insert or remove an element.
     */
public int remainingCapacity() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return capacity - count;
    } finally {
        lock.unlock();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock)

Example 13 with ReentrantLock

use of java.util.concurrent.locks.ReentrantLock in project Signal-Android by WhisperSystems.

the class LinkedBlockingDeque method drainTo.

/**
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     */
public int drainTo(Collection<? super E> c, int maxElements) {
    if (c == null)
        throw new NullPointerException();
    if (c == this)
        throw new IllegalArgumentException();
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        int n = Math.min(maxElements, count);
        for (int i = 0; i < n; i++) {
            // In this order, in case add() throws.
            c.add(first.item);
            unlinkFirst();
        }
        return n;
    } finally {
        lock.unlock();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock)

Example 14 with ReentrantLock

use of java.util.concurrent.locks.ReentrantLock in project Openfire by igniterealtime.

the class ArchiveIndexer method start.

public void start() {
    searchDir = new File(JiveGlobals.getHomeDirectory() + File.separator + MonitoringConstants.NAME + File.separator + "search");
    if (!searchDir.exists()) {
        searchDir.mkdirs();
    }
    boolean indexCreated = false;
    try {
        loadPropertiesFile(searchDir);
        // If the index already exists, use it.
        if (IndexReader.indexExists(searchDir)) {
            directory = FSDirectory.getDirectory(searchDir, false);
        } else // Otherwise, create a new index.
        {
            directory = FSDirectory.getDirectory(searchDir, true);
            indexCreated = true;
        }
    } catch (IOException ioe) {
        Log.error(ioe.getMessage(), ioe);
    }
    writerLock = new ReentrantLock(true);
    // for example).
    try {
        if (IndexReader.isLocked(directory)) {
            Log.warn("Archiving search index was locked, probably due to non-clean " + "application shutdown.");
            IndexReader.unlock(directory);
        }
    } catch (IOException ioe) {
        Log.error(ioe.getMessage(), ioe);
    }
    String modified = indexProperties.getProperty("lastModified");
    if (modified != null) {
        try {
            lastModified = Long.parseLong(modified);
        } catch (NumberFormatException nfe) {
        // Ignore.
        }
    }
    // If the index has never been updated, build it from scratch.
    if (lastModified == 0 || indexCreated) {
        taskEngine.submit(new Runnable() {

            public void run() {
                rebuildIndex();
            }
        });
    }
    indexUpdater = new TimerTask() {

        @Override
        public void run() {
            updateIndex();
        }
    };
    int updateInterval = JiveGlobals.getIntProperty("conversation.search.updateInterval", 15);
    taskEngine.scheduleAtFixedRate(indexUpdater, JiveConstants.MINUTE * 5, JiveConstants.MINUTE * updateInterval);
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) TimerTask(java.util.TimerTask) IOException(java.io.IOException) File(java.io.File)

Example 15 with ReentrantLock

use of java.util.concurrent.locks.ReentrantLock in project hadoop by apache.

the class TestDomainSocketWatcher method testStressInterruption.

@Test(timeout = 300000)
public void testStressInterruption() throws Exception {
    final int SOCKET_NUM = 250;
    final ReentrantLock lock = new ReentrantLock();
    final DomainSocketWatcher watcher = newDomainSocketWatcher(10);
    final ArrayList<DomainSocket[]> pairs = new ArrayList<DomainSocket[]>();
    final AtomicInteger handled = new AtomicInteger(0);
    final Thread adderThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                for (int i = 0; i < SOCKET_NUM; i++) {
                    DomainSocket[] pair = DomainSocket.socketpair();
                    watcher.add(pair[1], new DomainSocketWatcher.Handler() {

                        @Override
                        public boolean handle(DomainSocket sock) {
                            handled.incrementAndGet();
                            return true;
                        }
                    });
                    lock.lock();
                    try {
                        pairs.add(pair);
                    } finally {
                        lock.unlock();
                    }
                    TimeUnit.MILLISECONDS.sleep(1);
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });
    final Thread removerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            final Random random = new Random();
            try {
                while (handled.get() != SOCKET_NUM) {
                    lock.lock();
                    try {
                        if (!pairs.isEmpty()) {
                            int idx = random.nextInt(pairs.size());
                            DomainSocket[] pair = pairs.remove(idx);
                            if (random.nextBoolean()) {
                                pair[0].close();
                            } else {
                                watcher.remove(pair[1]);
                            }
                            TimeUnit.MILLISECONDS.sleep(1);
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (Throwable e) {
                LOG.error(e);
                throw new RuntimeException(e);
            }
        }
    });
    adderThread.start();
    removerThread.start();
    TimeUnit.MILLISECONDS.sleep(100);
    watcher.watcherThread.interrupt();
    Uninterruptibles.joinUninterruptibly(adderThread);
    Uninterruptibles.joinUninterruptibly(removerThread);
    Uninterruptibles.joinUninterruptibly(watcher.watcherThread);
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) ArrayList(java.util.ArrayList) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Aggregations

ReentrantLock (java.util.concurrent.locks.ReentrantLock)1524 Lock (java.util.concurrent.locks.Lock)125 Test (org.junit.Test)78 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)74 Condition (java.util.concurrent.locks.Condition)57 ArrayList (java.util.ArrayList)45 IOException (java.io.IOException)42 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)27 File (java.io.File)22 TimeoutException (java.util.concurrent.TimeoutException)19 Before (org.junit.Before)18 AtomicReference (java.util.concurrent.atomic.AtomicReference)17 HashMap (java.util.HashMap)16 CountDownLatch (java.util.concurrent.CountDownLatch)16 ExecutionException (java.util.concurrent.ExecutionException)15 List (java.util.List)14 AtomicLong (java.util.concurrent.atomic.AtomicLong)14 Map (java.util.Map)11 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)11 Pair (android.util.Pair)10