Java Code Examples for java.util.concurrent.locks.ReentrantLock#lock()

The following examples show how to use java.util.concurrent.locks.ReentrantLock#lock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CopyOnWriteArrayList.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void sort(Comparator<? super E> c) {
    final ReentrantLock lock = l.lock;
    lock.lock();
    try {
        int lo = offset;
        int hi = offset + size;
        Object[] elements = expectedArray;
        if (l.getArray() != elements)
            throw new ConcurrentModificationException();
        int len = elements.length;
        if (lo < 0 || hi > len)
            throw new IndexOutOfBoundsException();
        Object[] newElements = Arrays.copyOf(elements, len);
        @SuppressWarnings("unchecked") E[] es = (E[])newElements;
        Arrays.sort(es, lo, hi, c);
        l.setArray(expectedArray = newElements);
    } finally {
        lock.unlock();
    }
}
 
Example 2
Source File: CopyOnWriteArrayList.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public boolean removeIf(Predicate<? super E> filter) {
    if (filter == null) throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        if (len != 0) {
            int newlen = 0;
            Object[] temp = new Object[len];
            for (int i = 0; i < len; ++i) {
                @SuppressWarnings("unchecked") E e = (E) elements[i];
                if (!filter.test(e))
                    temp[newlen++] = e;
            }
            if (newlen != len) {
                setArray(Arrays.copyOf(temp, newlen));
                return true;
            }
        }
        return false;
    } finally {
        lock.unlock();
    }
}
 
Example 3
Source File: LinkedBlockingDeque.java    From WliveTV with Apache License 2.0 6 votes vote down vote up
/**
 * Atomically removes all of the elements from this deque.
 * The deque will be empty after this call returns.
 */
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();
    }
}
 
Example 4
Source File: ArrayBlockingQueue.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public String toString() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        int k = count;
        if (k == 0)
            return "[]";

        final Object[] items = this.items;
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (int i = takeIndex; ; ) {
            Object e = items[i];
            sb.append(e == this ? "(this Collection)" : e);
            if (--k == 0)
                return sb.append(']').toString();
            sb.append(',').append(' ');
            if (++i == items.length)
                i = 0;
        }
    } finally {
        lock.unlock();
    }
}
 
Example 5
Source File: LinkedBlockingDeque.java    From letv with Apache License 2.0 6 votes vote down vote up
public Object[] toArray() {
    ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] a = new Object[this.count];
        Node<E> p = this.first;
        int k = 0;
        while (p != null) {
            int k2 = k + 1;
            a[k] = p.item;
            p = p.next;
            k = k2;
        }
        return a;
    } finally {
        lock.unlock();
    }
}
 
Example 6
Source File: PriorityBlockingQueue.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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();
    if (maxElements <= 0)
        return 0;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        int n = Math.min(size, maxElements);
        for (int i = 0; i < n; i++) {
            c.add((E) queue[0]); // In this order, in case add() throws.
            dequeue();
        }
        return n;
    } finally {
        lock.unlock();
    }
}
 
Example 7
Source File: CopyOnWriteArrayList.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Inserts the specified element at the specified position in this
 * list. Shifts the element currently at that position (if any) and
 * any subsequent elements to the right (adds one to their indices).
 *
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public void add(int index, E element) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        if (index > len || index < 0)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+len);
        Object[] newElements;
        int numMoved = len - index;
        if (numMoved == 0)
            newElements = Arrays.copyOf(elements, len + 1);
        else {
            newElements = new Object[len + 1];
            System.arraycopy(elements, 0, newElements, 0, index);
            System.arraycopy(elements, index, newElements, index + 1,
                             numMoved);
        }
        newElements[index] = element;
        setArray(newElements);
    } finally {
        lock.unlock();
    }
}
 
Example 8
Source File: ScheduledThreadPoolExecutor.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public boolean remove(Object x) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        int i = indexOf(x);
        if (i < 0)
            return false;

        setIndex(queue[i], -1);
        int s = --size;
        RunnableScheduledFuture<?> replacement = queue[s];
        queue[s] = null;
        if (s != i) {
            siftDown(i, replacement);
            if (queue[i] == replacement)
                siftUp(i, replacement);
        }
        return true;
    } finally {
        lock.unlock();
    }
}
 
Example 9
Source File: LinkedBlockingDeque.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public boolean removeLastOccurrence(Object o) {
    if (o == null) return false;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (Node<E> p = last; p != null; p = p.prev) {
            if (o.equals(p.item)) {
                unlink(p);
                return true;
            }
        }
        return false;
    } finally {
        lock.unlock();
    }
}
 
Example 10
Source File: LinkedBlockingQueue.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a {@code LinkedBlockingQueue} with a capacity of
 * {@link Integer#MAX_VALUE}, initially containing the elements of the
 * given collection,
 * added in traversal order of the collection's iterator.
 *
 * @param c the collection of elements to initially contain
 * @throws NullPointerException if the specified collection or any
 *         of its elements are null
 */
public LinkedBlockingQueue(Collection<? extends E> c) {
    this(Integer.MAX_VALUE);
    final ReentrantLock putLock = this.putLock;
    putLock.lock(); // Never contended, but necessary for visibility
    try {
        int n = 0;
        for (E e : c) {
            if (e == null)
                throw new NullPointerException();
            if (n == capacity)
                throw new IllegalStateException("Queue full");
            enqueue(new Node<E>(e));
            ++n;
        }
        count.set(n);
    } finally {
        putLock.unlock();
    }
}
 
Example 11
Source File: ForkJoinTask.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Records exception and sets status.
 *
 * @return status on exit
 */
final int recordExceptionalCompletion(Throwable ex) {
    int s;
    if ((s = status) >= 0) {
        int h = System.identityHashCode(this);
        final ReentrantLock lock = exceptionTableLock;
        lock.lock();
        try {
            expungeStaleExceptions();
            ExceptionNode[] t = exceptionTable;
            int i = h & (t.length - 1);
            for (ExceptionNode e = t[i]; ; e = e.next) {
                if (e == null) {
                    t[i] = new ExceptionNode(this, ex, t[i]);
                    break;
                }
                if (e.get() == this) // already present
                    break;
            }
        } finally {
            lock.unlock();
        }
        s = setCompletion(EXCEPTIONAL);
    }
    return s;
}
 
Example 12
Source File: CopyOnWriteArrayList.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public ListIterator<E> listIterator(int index) {
    final ReentrantLock lock = l.lock;
    lock.lock();
    try {
        checkForComodification();
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        return new COWSubListIterator<E>(l, index, offset, size);
    } finally {
        lock.unlock();
    }
}
 
Example 13
Source File: ScheduledThreadPoolExecutor.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public Object[] toArray() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return Arrays.copyOf(queue, size, Object[].class);
    } finally {
        lock.unlock();
    }
}
 
Example 14
Source File: LinkedBlockingDeque.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public E peekLast() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (last == null) ? null : last.item;
    } finally {
        lock.unlock();
    }
}
 
Example 15
Source File: ThreadPoolExecutor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Transitions to TERMINATED state if either (SHUTDOWN and pool
 * and queue empty) or (STOP and pool empty).  If otherwise
 * eligible to terminate but workerCount is nonzero, interrupts an
 * idle worker to ensure that shutdown signals propagate. This
 * method must be called following any action that might make
 * termination possible -- reducing worker count or removing tasks
 * from the queue during shutdown. The method is non-private to
 * allow access from ScheduledThreadPoolExecutor.
 */
final void tryTerminate() {
    for (;;) {
        int c = ctl.get();
        if (isRunning(c) ||
            runStateAtLeast(c, TIDYING) ||
            (runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
            return;
        if (workerCountOf(c) != 0) { // Eligible to terminate
            interruptIdleWorkers(ONLY_ONE);
            return;
        }

        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
                try {
                    terminated();
                } finally {
                    ctl.set(ctlOf(TERMINATED, 0));
                    termination.signalAll();
                }
                return;
            }
        } finally {
            mainLock.unlock();
        }
        // else retry on failed CAS
    }
}
 
Example 16
Source File: CopyOnWriteArrayList.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Appends all of the elements in the specified collection that
 * are not already contained in this list, to the end of
 * this list, in the order that they are returned by the
 * specified collection's iterator.
 *
 * @param c collection containing elements to be added to this list
 * @return the number of elements added
 * @throws NullPointerException if the specified collection is null
 * @see #addIfAbsent(Object)
 */
public int addAllAbsent(Collection<? extends E> c) {
    Object[] cs = c.toArray();
    if (cs.length == 0)
        return 0;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        int added = 0;
        // uniquify and compact elements in cs
        for (int i = 0; i < cs.length; ++i) {
            Object e = cs[i];
            if (indexOf(e, elements, 0, len) < 0 &&
                indexOf(e, cs, 0, added) < 0)
                cs[added++] = e;
        }
        if (added > 0) {
            Object[] newElements = Arrays.copyOf(elements, len + added);
            System.arraycopy(cs, 0, newElements, len, added);
            setArray(newElements);
        }
        return added;
    } finally {
        lock.unlock();
    }
}
 
Example 17
Source File: ForkJoinTask.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes exception node and clears status.
 */
private void clearExceptionalCompletion() {
    int h = System.identityHashCode(this);
    final ReentrantLock lock = exceptionTableLock;
    lock.lock();
    try {
        ExceptionNode[] t = exceptionTable;
        int i = h & (t.length - 1);
        ExceptionNode e = t[i];
        ExceptionNode pred = null;
        while (e != null) {
            ExceptionNode next = e.next;
            if (e.get() == this) {
                if (pred == null)
                    t[i] = next;
                else
                    pred.next = next;
                break;
            }
            pred = e;
            e = next;
        }
        expungeStaleExceptions();
        status = 0;
    } finally {
        lock.unlock();
    }
}
 
Example 18
Source File: CopyOnWriteArrayList.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A version of remove(Object) using the strong hint that given
 * recent snapshot contains o at the given index.
 */
private boolean remove(Object o, Object[] snapshot, int index) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] current = getArray();
        int len = current.length;
        if (snapshot != current) findIndex: {
            int prefix = Math.min(index, len);
            for (int i = 0; i < prefix; i++) {
                if (current[i] != snapshot[i] && eq(o, current[i])) {
                    index = i;
                    break findIndex;
                }
            }
            if (index >= len)
                return false;
            if (current[index] == o)
                break findIndex;
            index = indexOf(o, current, index, len);
            if (index < 0)
                return false;
        }
        Object[] newElements = new Object[len - 1];
        System.arraycopy(current, 0, newElements, 0, index);
        System.arraycopy(current, index + 1,
                         newElements, index,
                         len - index - 1);
        setArray(newElements);
        return true;
    } finally {
        lock.unlock();
    }
}
 
Example 19
Source File: RPCChannelGroup.java    From rpc-java with Apache License 2.0 5 votes vote down vote up
public Channel getChannel(int index) {
    Validate.isTrue(index >=0 && index < connectionNum);
    if (isChannelValid(channelFutures[index])) {
        return channelFutures[index].channel();
    }

    ReentrantLock lock = locks[index];
    lock.lock();
    try {
        if (isChannelValid(channelFutures[index])) {
            return channelFutures[index].channel();
        }
        channelFutures[index] = connect(ip, port);
        if (channelFutures[index] == null) {
            return null;
        } else {
            channelFutures[index].sync();
            if (channelFutures[index].isSuccess()) {
                return channelFutures[index].channel();
            } else {
                return null;
            }
        }
    } catch (Exception ex) {
        LOG.warn("connect to {}:{} failed, msg={}", ip, port, ex.getMessage());
        return null;
    } finally {
        lock.unlock();
    }
}
 
Example 20
Source File: LinkedBlockingDeque.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
AbstractItr() {
    // set to initial position
    final ReentrantLock lock = LinkedBlockingDeque.this.lock;
    lock.lock();
    try {
        next = firstNode();
        nextItem = (next == null) ? null : next.item;
    } finally {
        lock.unlock();
    }
}