java.util.concurrent.locks.ReentrantLock#lock()源码实例Demo

下面列出了java.util.concurrent.locks.ReentrantLock#lock() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netty4.0.27Learn   文件: ForkJoinTask.java
/**
 * 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;
}
 
源代码2 项目: jdk8u-jdk   文件: LinkedBlockingQueue.java
/**
 * 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();
    }
}
 
源代码3 项目: openjdk-8-source   文件: LinkedBlockingDeque.java
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();
    }
}
 
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();
    }
}
 
源代码5 项目: openjdk-8-source   文件: CopyOnWriteArrayList.java
/**
 * 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();
    }
}
 
源代码6 项目: jdk8u-dev-jdk   文件: CopyOnWriteArrayList.java
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();
    }
}
 
源代码7 项目: hottub   文件: PriorityBlockingQueue.java
/**
 * @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();
    }
}
 
源代码8 项目: letv   文件: LinkedBlockingDeque.java
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();
    }
}
 
源代码9 项目: jdk8u-jdk   文件: ArrayBlockingQueue.java
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();
    }
}
 
源代码10 项目: WliveTV   文件: LinkedBlockingDeque.java
/**
 * 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();
    }
}
 
源代码11 项目: jdk8u-dev-jdk   文件: CopyOnWriteArrayList.java
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();
    }
}
 
public Object[] toArray() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return Arrays.copyOf(queue, size, Object[].class);
    } finally {
        lock.unlock();
    }
}
 
源代码13 项目: openjdk-jdk8u-backup   文件: LinkedBlockingDeque.java
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();
    }
}
 
源代码14 项目: rpc-java   文件: RPCChannelGroup.java
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();
    }
}
 
源代码15 项目: jdk8u-dev-jdk   文件: CopyOnWriteArrayList.java
/**
 * 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();
    }
}
 
源代码16 项目: TencentKona-8   文件: CopyOnWriteArrayList.java
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();
    }
}
 
源代码17 项目: openjdk-8-source   文件: LinkedBlockingDeque.java
public E peekLast() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (last == null) ? null : last.item;
    } finally {
        lock.unlock();
    }
}
 
源代码18 项目: hottub   文件: ThreadPoolExecutor.java
/**
 * 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
    }
}
 
/**
 * 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();
    }
}
 
源代码20 项目: TencentKona-8   文件: ForkJoinTask.java
/**
 * 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();
    }
}