List of usage examples for java.util.concurrent Semaphore Semaphore
public Semaphore(int permits)
From source file:org.alfresco.extension.bulkimport.impl.BulkImportThreadPoolExecutor.java
public BulkImportThreadPoolExecutor(final ThreadPauser pauser, final int threadPoolSize, final int queueCapacity, final long keepAliveTime, final TimeUnit keepAliveTimeUnit) { super(threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize, // Core pool size threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize, // Max pool size (same as core pool size) keepAliveTime <= 0 ? DEFAULT_KEEP_ALIVE_TIME : keepAliveTime, // Keep alive keepAliveTimeUnit == null ? DEFAULT_KEEP_ALIVE_TIME_UNIT : keepAliveTimeUnit, // Keep alive units new LinkedBlockingQueue<Runnable>(), // Queue of maximum size new BulkImportThreadFactory(), // Thread factory new ThreadPoolExecutor.AbortPolicy()); // Rejection handler (shouldn't ever be called, due to the use of a semaphone before task submission) this.queueCapacity = queueCapacity; this.pauser = pauser; final int queuePlusPoolSize = (queueCapacity <= 0 ? DEFAULT_QUEUE_CAPACITY : queueCapacity) + (threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize); this.queueSemaphore = new Semaphore(queuePlusPoolSize); if (debug(log)) debug(log, "Created new bulk import thread pool." + " Thread Pool Size=" + (threadPoolSize <= 0 ? DEFAULT_THREAD_POOL_SIZE : threadPoolSize) + ", Queue Capacity=" + ((queueCapacity <= 0 ? DEFAULT_QUEUE_CAPACITY : queueCapacity) + 2) + ", Keep Alive Time=" + (keepAliveTime <= 0 ? DEFAULT_KEEP_ALIVE_TIME : keepAliveTime) + " " + String.valueOf(keepAliveTimeUnit == null ? DEFAULT_KEEP_ALIVE_TIME_UNIT : keepAliveTimeUnit)); }
From source file:com.pinterest.rocksplicator.controller.WorkerPoolTest.java
@Test public void testAssignSameClusterConflict() throws Exception { Semaphore idleWorkersSemaphore = new Semaphore(0); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1)); WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, new TaskQueue() { });/*w w w. j a va2s . co m*/ Task task = getSleepIncrementTask(); workerPool.assignTask(task); Thread.sleep(2000); Assert.assertEquals(1, SleepIncrementTask.executionCounter.intValue()); workerPool.assignTask(task); Assert.assertEquals(1, idleWorkersSemaphore.availablePermits()); Thread.sleep(100); Assert.assertEquals(1, SleepIncrementTask.executionCounter.intValue()); Thread.sleep(1000); }
From source file:org.novelang.outfit.shell.ProcessShell.java
protected final void start(final long timeout, final TimeUnit timeUnit) throws IOException, InterruptedException, ProcessCreationException { final Semaphore startupSemaphore = new Semaphore(0); LOGGER.info("Starting process ", getNickname(), " in directory '", workingDirectory.getAbsolutePath(), "'..."); LOGGER.info("Arguments: ", processArguments); synchronized (stateLock) { ensureInState(State.READY); process = new ProcessBuilder().command(processArguments).directory(workingDirectory).start(); standardStreamWatcherThread = new Thread(threadGroup, createStandardOutputWatcher(process.getInputStream(), startupSemaphore), "standardWatcher-" + nickname); errorStreamWatcherThread = new Thread(threadGroup, createErrorOutputWatcher(process.getErrorStream()), "errorWatcher-" + nickname); standardStreamWatcherThread.setDaemon(true); standardStreamWatcherThread.start(); errorStreamWatcherThread.setDaemon(true); errorStreamWatcherThread.start(); LOGGER.debug("Waiting for startup sensor to detect startup line..."); startupSemaphore.tryAcquire(1, timeout, timeUnit); if (state == State.BROKEN) { throw new ProcessCreationException("Couldn't create " + getNickname()); } else {/*from ww w . j a v a 2 s . co m*/ state = State.RUNNING; } } LOGGER.info("Successfully launched process: ", getNickname(), " (it may be initializing now)."); }
From source file:xbird.engine.backend.QueryProcessor.java
public QueryProcessor(ResponseListener handler) { super(handler); this._throttle = new Semaphore(ThrottedRemoteSequenceProxy.NUM_THROTTLE); }
From source file:io.mindmaps.engine.loader.DistributedLoader.java
@Override public void setThreadsNumber(int number) { this.threadsNumber = number; // create availability map availability.keySet().forEach(h -> availability.put(h, new Semaphore(threadsNumber))); }
From source file:org.apache.hadoop.hbase.procedure2.TestProcedureExecutor.java
@Test(timeout = 60000) public void testWorkerStuck() throws Exception { // replace the executor final Configuration conf = new Configuration(htu.getConfiguration()); conf.setFloat("hbase.procedure.worker.add.stuck.percentage", 0.5f); conf.setInt("hbase.procedure.worker.monitor.interval.msec", 500); conf.setInt("hbase.procedure.worker.stuck.threshold.msec", 750); final int NUM_THREADS = 2; createNewExecutor(conf, NUM_THREADS); Semaphore latch1 = new Semaphore(2); latch1.acquire(2);/*from www . ja v a 2 s . c o m*/ BusyWaitProcedure busyProc1 = new BusyWaitProcedure(latch1); Semaphore latch2 = new Semaphore(2); latch2.acquire(2); BusyWaitProcedure busyProc2 = new BusyWaitProcedure(latch2); long busyProcId1 = procExecutor.submitProcedure(busyProc1); long busyProcId2 = procExecutor.submitProcedure(busyProc2); long otherProcId = procExecutor.submitProcedure(new NoopProcedure()); // wait until a new worker is being created int threads1 = waitThreadCount(NUM_THREADS + 1); LOG.info("new threads got created: " + (threads1 - NUM_THREADS)); assertEquals(NUM_THREADS + 1, threads1); ProcedureTestingUtility.waitProcedure(procExecutor, otherProcId); assertEquals(true, procExecutor.isFinished(otherProcId)); ProcedureTestingUtility.assertProcNotFailed(procExecutor, otherProcId); assertEquals(true, procExecutor.isRunning()); assertEquals(false, procExecutor.isFinished(busyProcId1)); assertEquals(false, procExecutor.isFinished(busyProcId2)); // terminate the busy procedures latch1.release(); latch2.release(); LOG.info("set keep alive and wait threads being removed"); procExecutor.setKeepAliveTime(500L, TimeUnit.MILLISECONDS); int threads2 = waitThreadCount(NUM_THREADS); LOG.info("threads got removed: " + (threads1 - threads2)); assertEquals(NUM_THREADS, threads2); // terminate the busy procedures latch1.release(); latch2.release(); // wait for all procs to complete ProcedureTestingUtility.waitProcedure(procExecutor, busyProcId1); ProcedureTestingUtility.waitProcedure(procExecutor, busyProcId2); ProcedureTestingUtility.assertProcNotFailed(procExecutor, busyProcId1); ProcedureTestingUtility.assertProcNotFailed(procExecutor, busyProcId2); }
From source file:com.bt.aloha.batchtest.v2.scenarios.InboundCallScenario.java
public void run(String scenarioId) { LOG.debug("starting scenario: " + scenarioId); acquireSyncSemaphore();/*ww w.j a v a 2 s . co m*/ String callLegId; synchronized (lock) { callLegId = this.outboundCallLegBean.createCallLeg(URI.create("sip:inboundcallscenario@robustness.com"), URI.create(getTestEndpoint())); callLegIdSemaphores.put(callLegId, new Semaphore(0)); callLegIdScenarioIds.put(callLegId, scenarioId); } ScenarioRunResult scenarioRunResult = new ScenarioRunResult(scenarioId, this.getName()); scenarioRunResult.setMessage("Just started"); connectCallLegAndWaitForCallLegConnectionFailedEvent(callLegId); }
From source file:org.apache.bookkeeper.benchmark.BenchThroughputLatency.java
public BenchThroughputLatency(int ensemble, int writeQuorumSize, int ackQuorumSize, byte[] passwd, int numberOfLedgers, int sendLimit, ClientConfiguration conf) throws KeeperException, IOException, InterruptedException { this.sem = new Semaphore(conf.getThrottleValue()); bk = new BookKeeper(conf); this.counter = new AtomicLong(0); this.numberOfLedgers = numberOfLedgers; this.sendLimit = sendLimit; this.latencies = new long[sendLimit]; try {//w ww . j ava 2 s. c o m lh = new LedgerHandle[this.numberOfLedgers]; for (int i = 0; i < this.numberOfLedgers; i++) { lh[i] = bk.createLedger(ensemble, writeQuorumSize, ackQuorumSize, BookKeeper.DigestType.CRC32, passwd); LOG.debug("Ledger Handle: " + lh[i].getId()); } } catch (BKException e) { e.printStackTrace(); } }
From source file:org.minig.imap.impl.ClientSupport.java
public ClientSupport(IoHandler handler) { this.lock = new Semaphore(1); this.handler = handler; this.tagsProducer = new TagProducer(); this.lastResponses = Collections.synchronizedList(new LinkedList<IMAPResponse>()); }
From source file:AlgorithmAnimation.java
/** * Constructs a Sorter./* ww w . j a v a 2 s . c o m*/ * @param values the array to be sorted * @param comp the component on which to display the sorting progress */ public Sorter(ArrayComponent comp) { values = new Double[VALUES_LENGTH]; for (int i = 0; i < values.length; i++) values[i] = new Double(Math.random()); this.component = comp; this.gate = new Semaphore(1); this.run = false; }