java.util.concurrent.locks.ReentrantLock Java Examples

The following examples show how to use java.util.concurrent.locks.ReentrantLock. 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: ArrayBlockingQueue.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns {@code true} if this queue contains the specified element.
 * More formally, returns {@code true} if and only if this queue contains
 * at least one element {@code e} such that {@code o.equals(e)}.
 *
 * @param o object to be checked for containment in this queue
 * @return {@code true} if this queue contains the specified element
 */
public boolean contains(Object o) {
    if (o == null) return false;
    final Object[] items = this.items;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        if (count > 0) {
            final int putIndex = this.putIndex;
            int i = takeIndex;
            do {
                if (o.equals(items[i]))
                    return true;
                if (++i == items.length)
                    i = 0;
            } while (i != putIndex);
        }
        return false;
    } finally {
        lock.unlock();
    }
}
 
Example #2
Source File: PriorityBlockingQueue.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Identity-based version for use in Itr.remove
 */
void removeEQ(Object o) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] array = queue;
        for (int i = 0, n = size; i < n; i++) {
            if (o == array[i]) {
                removeAt(i);
                break;
            }
        }
    } finally {
        lock.unlock();
    }
}
 
Example #3
Source File: LinkedBlockingDeque.java    From openjdk-jdk8u-backup with GNU General Public License v2.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: MemoryEventStoreWithBuffer.java    From canal with Apache License 2.0 6 votes vote down vote up
public void put(List<Event> data) throws InterruptedException, CanalStoreException {
    if (data == null || data.isEmpty()) {
        return;
    }

    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        try {
            while (!checkFreeSlotAt(putSequence.get() + data.size())) { // 检查是否有空位
                notFull.await(); // wait until not full
            }
        } catch (InterruptedException ie) {
            notFull.signal(); // propagate to non-interrupted thread
            throw ie;
        }
        doPut(data);
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    } finally {
        lock.unlock();
    }
}
 
Example #5
Source File: PriorityBlockingAggregatorQueue.java    From tilt-game-android with MIT License 6 votes vote down vote up
public void addQueue(final int pPriority, final int pCapacity, final int pInitialCapacity) {
	if (pCapacity <= 0) {
		throw new IllegalArgumentException("pCapacity must be greater than 0.");
	}

	if (pInitialCapacity <= 0) {
		throw new IllegalArgumentException("pInitialCapacity must be greater than 0.");
	}

	final ReentrantLock lock = this.mLock;
	lock.lock();

	try {
		this.mQueues.put(pPriority, new CircularList<T>(pInitialCapacity));
		this.mQueueCapacities.put(pPriority, pCapacity);
		this.mNotFullConditions.put(pPriority, this.mLock.newCondition());
	} finally {
		lock.unlock();
	}
}
 
Example #6
Source File: LinkedBlockingDeque.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public boolean removeFirstOccurrence(Object o) {
    if (o == null) return false;
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (Node<E> p = first; p != null; p = p.next) {
            if (o.equals(p.item)) {
                unlink(p);
                return true;
            }
        }
        return false;
    } finally {
        lock.unlock();
    }
}
 
Example #7
Source File: ThreadPoolExecutor.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public boolean awaitTermination(long timeout, TimeUnit unit)
    throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        for (;;) {
            if (runStateAtLeast(ctl.get(), TERMINATED))
                return true;
            if (nanos <= 0)
                return false;
            nanos = termination.awaitNanos(nanos);
        }
    } finally {
        mainLock.unlock();
    }
}
 
Example #8
Source File: EventBroker.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
@Inject
public EventBroker(
    ErrorReporter errorReporterRef,
    CommonSerializer commonSerializerRef,
    WatchStore watchStoreRef,
    Map<String, EventSerializer> eventSerializersRef,
    Map<String, EventSerializerDescriptor> eventSerializerDescriptorsRef
)
{
    errorReporter = errorReporterRef;
    commonSerializer = commonSerializerRef;
    watchStore = watchStoreRef;
    eventSerializers = eventSerializersRef;
    eventSerializerDescriptors = eventSerializerDescriptorsRef;

    watchLock = new ReentrantLock();
}
 
Example #9
Source File: ArrayBlockingQueue.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Atomically removes all of the elements from this queue.
 * The queue will be empty after this call returns.
 */
public void clear() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        int k = count;
        if (k > 0) {
            final Object[] items = this.items;
            final int putIndex = this.putIndex;
            int i = takeIndex;
            do {
                items[i] = null;
                if (++i == items.length) i = 0;
            } while (i != putIndex);
            takeIndex = putIndex;
            count = 0;
            if (itrs != null)
                itrs.queueIsEmpty();
            for (; k > 0 && lock.hasWaiters(notFull); k--)
                notFull.signal();
        }
    } finally {
        lock.unlock();
    }
}
 
Example #10
Source File: ForkJoinTask.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * If lock is available, poll stale refs and remove them.
 * Called from ForkJoinPool when pools become quiescent.
 */
static final void helpExpungeStaleExceptions() {
    final ReentrantLock lock = exceptionTableLock;
    if (lock.tryLock()) {
        try {
            expungeStaleExceptions();
        } finally {
            lock.unlock();
        }
    }
}
 
Example #11
Source File: ThreadPoolExecutor.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the approximate total number of tasks that have ever been
 * scheduled for execution. Because the states of tasks and
 * threads may change dynamically during computation, the returned
 * value is only an approximation.
 *
 * @return the number of tasks
 */
public long getTaskCount() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        long n = completedTaskCount;
        for (Worker w : workers) {
            n += w.completedTasks;
            if (w.isLocked())
                ++n;
        }
        return n + workQueue.size();
    } finally {
        mainLock.unlock();
    }
}
 
Example #12
Source File: ConcreteResourceRegistration.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/** Constructor for a non-root MRR */
ConcreteResourceRegistration(final String valueString, final NodeSubregistry parent, final ResourceDefinition definition,
                             final AccessConstraintUtilizationRegistry constraintUtilizationRegistry,
                             final boolean ordered, CapabilityRegistry capabilityRegistry) {
    super(valueString, parent);
    this.constraintUtilizationRegistry = constraintUtilizationRegistry;
    this.capabilityRegistry = capabilityRegistry;
    this.resourceDefinition = definition;
    // If our parent is runtime-only, so are we, otherwise follow the definition
    this.runtimeOnly = parent.isRuntimeOnly() || definition.isRuntime();
    this.accessConstraintDefinitions = buildAccessConstraints();
    this.ordered = ordered;
    // For non-root MRRs we don't expect much in the way of concurrent reads in performance
    // critical situations, so we want lock/unlock to be as simple and fast as possible
    // So we just use a single non-r/w lock for both reads and writes
    this.readLock = this.writeLock = new ReentrantLock();
}
 
Example #13
Source File: LinkedBlockingDeque.java    From WliveTV with Apache License 2.0 6 votes vote down vote up
/**
 * @throws NullPointerException {@inheritDoc}
 * @throws InterruptedException {@inheritDoc}
 */
public boolean offerFirst(E e, long timeout, TimeUnit unit)
        throws InterruptedException {
    if (e == null) throw new NullPointerException();
    Node<E> node = new Node<E>(e);
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (!linkFirst(node)) {
            if (nanos <= 0)
                return false;
            nanos = notFull.awaitNanos(nanos);
        }
        return true;
    } finally {
        lock.unlock();
    }
}
 
Example #14
Source File: PostgreSQLHeartbeat.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void stop() {
	final ReentrantLock lock = this.lock;
	lock.lock();
	try {
		if (isStop.compareAndSet(false, true)) {
			if (isChecking.get()) {
				// nothing
			} else {
				PostgreSQLDetector detector = this.detector;
				if (detector != null) {
					detector.quit();
					isChecking.set(false);
				}
			}
		}
	} finally {
		lock.unlock();
	}
}
 
Example #15
Source File: LinkedBlockingDeque.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public E pollLast(long timeout, TimeUnit unit)
    throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        E x;
        while ( (x = unlinkLast()) == null) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        return x;
    } finally {
        lock.unlock();
    }
}
 
Example #16
Source File: CaptureCollector.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Called to alert the {@link CaptureCollector} that the jpeg capture has begun.
 *
 * @param timestamp the time of the jpeg capture.
 * @return the {@link RequestHolder} for the request associated with this capture.
 */
public RequestHolder jpegCaptured(long timestamp) {
    final ReentrantLock lock = this.mLock;
    lock.lock();
    try {
        CaptureHolder h = mJpegCaptureQueue.poll();
        if (h == null) {
            Log.w(TAG, "jpegCaptured called with no jpeg request on queue!");
            return null;
        }
        h.setJpegTimestamp(timestamp);
        return h.mRequest;
    } finally {
        lock.unlock();
    }
}
 
Example #17
Source File: ThreadPoolExecutor.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the approximate total number of tasks that have ever been
 * scheduled for execution. Because the states of tasks and
 * threads may change dynamically during computation, the returned
 * value is only an approximation.
 *
 * @return the number of tasks
 */
public long getTaskCount() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        long n = completedTaskCount;
        for (Worker w : workers) {
            n += w.completedTasks;
            if (w.isLocked())
                ++n;
        }
        return n + workQueue.size();
    } finally {
        mainLock.unlock();
    }
}
 
Example #18
Source File: ScheduledThreadPoolExecutor.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
public void clear() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (int i = 0; i < size; i++) {
            RunnableScheduledFuture<?> t = queue[i];
            if (t != null) {
                queue[i] = null;
                setIndex(t, -1);
            }
        }
        size = 0;
    } finally {
        lock.unlock();
    }
}
 
Example #19
Source File: CopyOnWriteArrayList.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public List<E> subList(int fromIndex, int toIndex) {
    final ReentrantLock lock = l.lock;
    lock.lock();
    try {
        checkForComodification();
        if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
            throw new IndexOutOfBoundsException();
        return new COWSubList<E>(l, fromIndex + offset,
                                 toIndex + offset);
    } finally {
        lock.unlock();
    }
}
 
Example #20
Source File: LinkedBlockingDeque.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
public void forEachRemaining(Consumer<? super E> action) {
    if (action == null) throw new NullPointerException();
    final LinkedBlockingDeque<E> q = this.queue;
    final ReentrantLock lock = q.lock;
    if (!exhausted) {
        exhausted = true;
        Node<E> p = current;
        do {
            E e = null;
            lock.lock();
            try {
                if (p == null)
                    p = q.first;
                while (p != null) {
                    e = p.item;
                    p = p.next;
                    if (e != null)
                        break;
                }
            } finally {
                lock.unlock();
            }
            if (e != null)
                action.accept(e);
        } while (p != null);
    }
}
 
Example #21
Source File: ThreadPoolExecutor.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initiates an orderly shutdown in which previously submitted
 * tasks are executed, but no new tasks will be accepted.
 * Invocation has no additional effect if already shut down.
 *
 * <p>This method does not wait for previously submitted tasks to
 * complete execution.  Use {@link #awaitTermination awaitTermination}
 * to do that.
 *
 * @throws SecurityException {@inheritDoc}
 */
public void shutdown() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        checkShutdownAccess();
        advanceRunState(SHUTDOWN);
        interruptIdleWorkers();
        onShutdown(); // hook for ScheduledThreadPoolExecutor
    } finally {
        mainLock.unlock();
    }
    tryTerminate();
}
 
Example #22
Source File: SimpleTEDB.java    From netphony-topology with Apache License 2.0 5 votes vote down vote up
public SimpleTEDB(){
	log=LoggerFactory.getLogger("TEDBParser");		
	registeredAlgorithms= new ArrayList<TEDListener>();
	registeredAlgorithmssson= new ArrayList<SSONListener>();
	TEDBlock=new ReentrantLock();
	NodeTable = new Hashtable<Object, Node_Info>();
}
 
Example #23
Source File: PriorityBlockingQueue.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public E peek() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (size == 0) ? null : (E) queue[0];
    } finally {
        lock.unlock();
    }
}
 
Example #24
Source File: BasicManagedDataSource.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void setJdbcUrl(final String string) {
    final ReentrantLock l = lock;
    l.lock();
    try {
        super.setUrl(string);
    } finally {
        l.unlock();
    }
}
 
Example #25
Source File: PriorityBlockingQueue.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
public E peek() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (size == 0) ? null : (E) queue[0];
    } finally {
        lock.unlock();
    }
}
 
Example #26
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 #27
Source File: SynchronizerLockingThread.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
protected void setExpectedResult(Lock waitingLock,
                                 int numOwnedMonitors,
                                 Map<String, Lock[]> ownedMonitors,
                                 Condition waitingSync,
                                 int numOwnedSyncs,
                                 Map<String, ReentrantLock[]> ownedSyncs) {
    this.waitingLock = waitingLock;
    this.numOwnedMonitors = numOwnedMonitors;
    this.ownedMonitors = ownedMonitors;
    this.waitingSync = waitingSync;
    this.numOwnedSyncs = numOwnedSyncs;
    this.ownedSyncs = ownedSyncs;
}
 
Example #28
Source File: ScheduledThreadPoolExecutor.java    From Bytecoder with Apache License 2.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 #29
Source File: PriorityBlockingQueue.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Atomically removes all of the elements from this queue.
 * The queue will be empty after this call returns.
 */
public void clear() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] array = queue;
        int n = size;
        size = 0;
        for (int i = 0; i < n; i++)
            array[i] = null;
    } finally {
        lock.unlock();
    }
}
 
Example #30
Source File: DelayQueue.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes a single instance of the specified element from this
 * queue, if it is present, whether or not it has expired.
 */
public boolean remove(Object o) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return q.remove(o);
    } finally {
        lock.unlock();
    }
}