当前位置: 首页>>代码示例>>Java>>正文


Java ReentrantLock类代码示例

本文整理汇总了Java中java.util.concurrent.locks.ReentrantLock的典型用法代码示例。如果您正苦于以下问题:Java ReentrantLock类的具体用法?Java ReentrantLock怎么用?Java ReentrantLock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ReentrantLock类属于java.util.concurrent.locks包,在下文中一共展示了ReentrantLock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: writeObject

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
/**
 * Save the state of this deque to a stream (that is, serialize it).
 *
 * @param s the stream
 * @serialData The capacity (int), followed by elements (each an
 * <tt>Object</tt>) in the proper order, followed by a null
 */
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
    final ReentrantLock reentrantLock = this.lock;
    reentrantLock.lock();
    try {
        // Write out capacity and any hidden stuff
        s.defaultWriteObject();
        // Write out all elements in the proper order.
        for (Node<E> p = first; p != null; p = p.next)
            s.writeObject(p.item);
        // Use trailing null as sentinel
        s.writeObject(null);
    } finally {
        reentrantLock.unlock();
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:23,代码来源:FairLinkedBlockingDeque.java

示例2: removeFirstOccurrence

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
public boolean removeFirstOccurrence(Object o) {
    if (o == null) {
        return false;
    }
    ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (Node<E> p = this.first; p != null; p = p.next) {
            if (o.equals(p.item)) {
                unlink(p);
                return true;
            }
        }
        lock.unlock();
        return false;
    } finally {
        lock.unlock();
    }
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:20,代码来源:LinkedBlockingDeque.java

示例3: take

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
public E take() throws InterruptedException {
	int c = -1;
	AtomicInteger count = this.count;
	ReentrantLock takeLock = this.takeLock;
	takeLock.lockInterruptibly();
	E x;
	try {
		try {
			while (count.get() == 0)
				this.notEmpty.await();
		} catch (InterruptedException ie) {
			this.notEmpty.signal();
			throw ie;
		}

		x = extract();
		c = count.getAndDecrement();
		if (c > 1)
			this.notEmpty.signal();
	} finally {
		takeLock.unlock();
	}
	return x;
}
 
开发者ID:jiangzongyao,项目名称:kettle_support_kettle8.0,代码行数:25,代码来源:ListQueue.java

示例4: getTaskCount

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
/**
 * 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();
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:ThreadPoolExecutor.java

示例5: AppStateStorage

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
/**
 * Create a AppStateStorage
 * @param context master context
 * @param writeDir storage file directory
 * @param fs 
 */
public AppStateStorage(AMContext context, String writeDir, FileSystem fs){
  super("app-state-writter");
  LOG.info("writeDir=" + writeDir);
  this.context = context;
  this.writeDir = writeDir;
  this.writeDirPath = new Path(writeDir);
  this.fs = fs;
  
  splitFilePath = new Path(writeDirPath, splitFileName);
  matrixMetaLock = new ReentrantLock();
  taskMetaLock = new ReentrantLock();
  psMetaLock = new ReentrantLock();
  
  writeIntervalMS = context.getConf().getInt(
      AngelConf.ANGEL_AM_WRITE_STATE_INTERVAL_MS,
      AngelConf.DEFAULT_ANGEL_AM_WRITE_STATE_INTERVAL_MS);
  this.stopped = new AtomicBoolean(false);
}
 
开发者ID:Tencent,项目名称:angel,代码行数:25,代码来源:AppStateStorage.java

示例6: take

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
/** Returns the element with the next timestamp, waiting until it is available.
    *
    * <p>Note that because of the reordering semantics, an invocation of this method
    * on a {@linkplain #isEmpty() nonempty} queue might block nonetheless.
    *
    * @return the element with the next timestamp.
    */
public E take() throws InterruptedException {
	final ReentrantLock lock = this.lock;
	lock.lockInterruptibly();
	try {
		while (a[start] == null) nextObjectReady.await();
		@SuppressWarnings("unchecked")
		final E x = (E)a[start];
		a[start] = null;
		start = start + 1 & mask;
		--count;
		timeStamp++;
		newSpaceAvailable.signalAll();
		return x;
	}
	finally {
		lock.unlock();
	}
}
 
开发者ID:LAW-Unimi,项目名称:BUbiNG,代码行数:26,代码来源:ReorderingBlockingQueue.java

示例7: removeEQ

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
/**
 * 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();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:19,代码来源:PriorityBlockingQueue.java

示例8: tReentrantLock

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
public void tReentrantLock() {
    System.currentTimeMillis();
    ReentrantLock lock = new ReentrantLock();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < 10000000; i++) {
        if (lock.tryLock()) {
            try {
                // ...
            } finally {
                lock.unlock();
            }
        }
    }
    long t2 = System.currentTimeMillis();

    System.out.println("take time:" + (t2 - t1) + " ms.");
}
 
开发者ID:actiontech,项目名称:dble,代码行数:19,代码来源:LockPerfMain.java

示例9: AsyncTraceDispatcher

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
public AsyncTraceDispatcher(Properties properties) {
    int queueSize = Integer.parseInt(properties.getProperty(OnsTraceConstants.AsyncBufferSize, "2048"));
    // queueSize 取大于或等于 value 的 2 的 n 次方数
    queueSize = 1 << (32 - Integer.numberOfLeadingZeros(queueSize - 1));
    this.queueSize = queueSize;
    this.entries = new Object[queueSize];
    this.indexMask = queueSize - 1;
    /**
     * 默认的消费者唤醒阈值,这个值需要让消费者能较持续的有事情做, 这个值设置过小,会导致生产者频繁唤起消费者;
     * 设置过大,可能导致生产者速度过快导致队列满丢日志的问题。
     */
    this.notifyThreshold = Integer.parseInt(properties.getProperty(OnsTraceConstants.WakeUpNum, "1"));
    this.putIndex = new AtomicLong(0L);
    this.discardCount = new AtomicLong(0L);
    this.takeIndex = new AtomicLong(0L);

    this.running = new AtomicBoolean(false);

    this.lock = new ReentrantLock(false);
    this.notEmpty = lock.newCondition();
}
 
开发者ID:maihaoche,项目名称:rocketmq-spring-boot-starter,代码行数:22,代码来源:AsyncTraceDispatcher.java

示例10: testResourceIsInUseHasAnActiveApp

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
@Test
public void testResourceIsInUseHasAnActiveApp() throws Exception {
  FileSystem fs = mock(FileSystem.class);
  CleanerMetrics metrics = mock(CleanerMetrics.class);
  SCMStore store = mock(SCMStore.class);

  FileStatus resource = mock(FileStatus.class);
  when(resource.getPath()).thenReturn(new Path(ROOT + "/a/b/c/abc"));
  // resource is stale
  when(store.isResourceEvictable(isA(String.class), isA(FileStatus.class)))
      .thenReturn(true);
  // but still has appIds
  when(store.removeResource(isA(String.class))).thenReturn(false);

  CleanerTask task =
      createSpiedTask(fs, store, metrics, new ReentrantLock());

  // process the resource
  task.processSingleResource(resource);

  // metrics should record a processed file (but not delete)
  verify(metrics).reportAFileProcess();
  verify(metrics, never()).reportAFileDelete();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:25,代码来源:TestCleanerTask.java

示例11: contains

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
public boolean contains(Object o) {
    if (o == null) {
        return false;
    }
    ReentrantLock lock = this.lock;
    lock.lock();
    try {
        for (Node<E> p = this.first; p != null; p = p.next) {
            if (o.equals(p.item)) {
                return true;
            }
        }
        lock.unlock();
        return false;
    } finally {
        lock.unlock();
    }
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:19,代码来源:LinkedBlockingDeque.java

示例12: clear

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
/**
 * Atomically removes all of the elements from this deque. The deque will be
 * empty after this call returns.
 */
public void clear() {
    final ReentrantLock reentrantLock = this.lock;
    reentrantLock.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 {
        reentrantLock.unlock();
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:23,代码来源:FairLinkedBlockingDeque.java

示例13: AbstractConnPool

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
public AbstractConnPool(
        final ConnFactory<T, C> connFactory,
        int defaultMaxPerRoute,
        int maxTotal) {
    super();
    if (connFactory == null) {
        throw new IllegalArgumentException("Connection factory may not null");
    }
    if (defaultMaxPerRoute <= 0) {
        throw new IllegalArgumentException("Max per route value may not be negative or zero");
    }
    if (maxTotal <= 0) {
        throw new IllegalArgumentException("Max total value may not be negative or zero");
    }
    this.lock = new ReentrantLock();
    this.connFactory = connFactory;
    this.routeToPool = new HashMap<T, RouteSpecificPool<T, C, E>>();
    this.leased = new HashSet<E>();
    this.available = new LinkedList<E>();
    this.pending = new LinkedList<PoolEntryFuture<E>>();
    this.maxPerRoute = new HashMap<T, Integer>();
    this.defaultMaxPerRoute = defaultMaxPerRoute;
    this.maxTotal = maxTotal;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:25,代码来源:AbstractConnPool.java

示例14: clear

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
/**
 * 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();
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:23,代码来源:LinkedBlockingDeque.java

示例15: toArray

import java.util.concurrent.locks.ReentrantLock; //导入依赖的package包/类
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();
    }
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:19,代码来源:LinkedBlockingDeque.java


注:本文中的java.util.concurrent.locks.ReentrantLock类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。