Example usage for java.util.concurrent.locks ReentrantLock ReentrantLock

List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock

Introduction

In this page you can find the example usage for java.util.concurrent.locks ReentrantLock ReentrantLock.

Prototype

public ReentrantLock() 

Source Link

Document

Creates an instance of ReentrantLock .

Usage

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>See {@link #testAsyncSuccess()}.</p>
 *///from w w w  . j a  v  a  2  s  .  c om
private void successScenario() throws InterruptedException {

    String subpath = "/asyncsuccess", body = "hello";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200).withBody(body)));

    final Object[] content = new Object[2];

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    String result = asyncEndpoint.asyncSuccess(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String deserializedContent) {

            lock.lock();

            content[0] = httpResponse;
            content[1] = deserializedContent;

            condition.signal();
            lock.unlock();
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    assertTrue(content[0] != null);
    assertTrue(content[1] != null);
    assertTrue(content[1].equals(body));

    assertNull(result);
}

From source file:org.zaproxy.zap.extension.spider.SpiderScanController.java

public SpiderScanController(ExtensionSpider extension) {
    this.spiderScansLock = new ReentrantLock();
    this.extension = extension;
    this.spiderScanMap = new HashMap<>();
    this.spiderScanList = new ArrayList<SpiderScan>();
}

From source file:org.apache.http.impl.conn.tsccm.AbstractConnPool.java

/**
 * Creates a new connection pool.//from www.  j a  va2  s.c o m
 */
protected AbstractConnPool() {
    super();
    this.log = LogFactory.getLog(getClass());
    this.leasedConnections = new HashSet<BasicPoolEntry>();
    this.idleConnHandler = new IdleConnectionHandler();
    this.poolLock = new ReentrantLock();
}

From source file:com.sworddance.taskcontrol.TaskControl.java

@SuppressWarnings("unchecked")
public TaskControl(Comparator<PrioritizedTask> activeComparator, int maxThreads, ThreadFactory threadFactory,
        Log log) {//from  ww w .j  a v  a2 s  .  c  o m
    this.log = log;
    ApplicationIllegalArgumentException.notNull(activeComparator, "activeComparator");
    this.eligibleTasks = new PriorityBlockingQueue<PrioritizedTask>(20, activeComparator);
    this.stateChangeNotificator = new ReentrantLock();
    this.newTasks = this.stateChangeNotificator.newCondition();
    this.runningTasks = new AtomicInteger(0);
    this.threadFactory = threadFactory;
    int keepAliveTime = 10;

    int corePoolSize = 1;
    this.executor = new ThreadPoolExecutor(corePoolSize, Math.max(corePoolSize, maxThreads), keepAliveTime,
            MICROSECONDS, (BlockingQueue) this.eligibleTasks, threadFactory);
    this.stayActive = true;
}

From source file:com.netflix.config.ConcurrentMapConfiguration.java

/**
 * Create an instance with an empty map.
 *//*from  w w w  .  j  ava2  s. c  om*/
public ConcurrentMapConfiguration() {
    map = new ConcurrentHashMap<String, Object>();
    for (int i = 0; i < NUM_LOCKS; i++) {
        locks[i] = new ReentrantLock();
    }
}

From source file:RefinableHashSet.java

/**
 * double the set size/* ww w  .  ja v  a2s .  c  om*/
 */
@Override
public void resize() {
    int oldCapacity = table.length;
    int newCapacity = 2 * oldCapacity;
    Thread me = Thread.currentThread();
    if (owner.compareAndSet(null, me, false, true)) {
        try {
            if (table.length != oldCapacity) { // someone else resized first
                return;
            }
            quiesce();
            List<T>[] oldTable = table;
            table = (List<T>[]) new List[newCapacity];
            for (int i = 0; i < newCapacity; i++)
                table[i] = new ArrayList<T>();
            locks = new ReentrantLock[newCapacity];
            for (int j = 0; j < locks.length; j++) {
                locks[j] = new ReentrantLock();
            }
            initializeFrom(oldTable);
        } finally {
            owner.set(null, false); // restore prior state
        }
    }
}

From source file:edu.unc.lib.dl.admin.collect.DepositBinCollectorTest.java

@Before
public void setup() throws Exception {
    initMocks(this);

    depositsDirectory = tmpFolder.newFolder("deposits");
    binDirectory = tmpFolder.newFolder("bin");

    List<String> binPaths = Arrays.asList(binDirectory.getAbsolutePath());
    when(config.getPaths()).thenReturn(binPaths);
    when(config.getKeyLock()).thenReturn(new ReentrantLock());

    Map<String, DepositBinConfiguration> configs = new HashMap<String, DepositBinConfiguration>();
    configs.put("etd", config);

    manager = new DepositBinCollector();
    setField(manager, "depositsDirectory", depositsDirectory);
    setField(manager, "depositStatusFactory", depositStatusFactory);
    setField(manager, "configs", configs);
}

From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java

public DefaultSession(Long id, int inBufferSize, int outBufferSize) {
    this.id = id;
    this.state = SessionStateEnum.WAVERIDER_SESSION_STATE_FREE;
    this.inBufferSize = inBufferSize;
    this.outBufferSize = outBufferSize;
    this.runLock = new ReentrantLock();
    this.run = runLock.newCondition();
    this.isRun = false;
    threadFactory = new WaveriderThreadFactory(SESSION_THREAD_NAME_PREFIX + "-" + String.valueOf(id), null,
            true);/*w ww. ja v  a2s  .  c o m*/
}

From source file:org.zaproxy.zap.extension.spider.SpiderScan.java

public SpiderScan(ExtensionSpider extension, SpiderParam spiderParams, Target target, URI spiderURI,
        User scanUser, int scanId) {
    lock = new ReentrantLock();
    this.scanId = scanId;

    numberOfURIsFound = new AtomicInteger();
    foundURIs = Collections.synchronizedSet(new HashSet<String>());
    resourcesFound = Collections.synchronizedList(new ArrayList<SpiderResource>());
    foundURIsOutOfScope = Collections.synchronizedSet(new HashSet<String>());

    state = State.NOT_STARTED;/* ww  w. j a v  a  2  s  . c  o m*/

    spiderThread = new SpiderThread(extension, spiderParams, "SpiderApi-" + scanId, this);

    spiderThread.setStartURI(spiderURI);
    spiderThread.setStartNode(target.getStartNode());
    spiderThread.setScanContext(target.getContext());
    spiderThread.setScanAsUser(scanUser);
    spiderThread.setJustScanInScope(target.isInScopeOnly());
    spiderThread.setScanChildren(target.isRecurse());
}

From source file:org.apache.jmeter.control.CriticalSectionController.java

/**
 * If lock exists returns it, otherwise creates one, puts it in LOCK_MAP 
 * then returns it/*from   www  . j av  a  2 s.c o m*/
 * 
 * @return {@link ReentrantLock}
 */
private ReentrantLock getOrCreateLock() {
    String lockName = getLockName();
    ReentrantLock lock = LOCK_MAP.get(lockName);
    ReentrantLock prev = null;
    if (lock != null) {
        return lock;
    }
    lock = new ReentrantLock();
    prev = LOCK_MAP.putIfAbsent(lockName, lock);
    return prev == null ? lock : prev;
}