@Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (unit == null) { throw new NullPointerException("unit"); } if (inEventLoop()) { throw new IllegalStateException("cannot await termination of the current thread"); } if (threadLock.tryAcquire(timeout, unit)) { threadLock.release(); } return isTerminated(); }
/** {@inheritDoc} */ @Override public boolean start(IScope scope) { if (lock == null) { lock = new Semaphore(1, true); } try { lock.tryAcquire(1, TimeUnit.SECONDS); return super.start(scope); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.release(); } return false; }
public class BoundedExecutor { private final Executor exec; private final Semaphore semaphore; public BoundedExecutor(Executor exec, int bound) { this.exec = exec; this.semaphore = new Semaphore(bound); } public void submitTask(final Runnable command) throws InterruptedException, RejectedExecutionException { semaphore.acquire(); try { exec.execute(new Runnable() { public void run() { try { command.run(); } finally { semaphore.release(); } } }); } catch (RejectedExecutionException e) { semaphore.release(); throw e; } } }
@Test public void testRunningJobIsInterruptedAfterShutdownNow() throws InterruptedException { BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); ExecutorService service = Executors.newSingleThreadExecutor(); try { PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, 1); final Semaphore jobSemaphore = new Semaphore(0); final Semaphore testSemaphore = new Semaphore(0); final AtomicBoolean interrupted = new AtomicBoolean(); executor.submit(() -> { testSemaphore.release(); try { jobSemaphore.acquire(); } catch (InterruptedException e) { interrupted.set(true); } }); testSemaphore.acquireUninterruptibly(); assertThat(executor.shutdownNow(), empty()); assertThat(executor.awaitTermination(2, MINUTES), is(true)); assertThat(executor.isShutdown(), is(true)); assertThat(executor.isTerminated(), is(true)); assertThat(jobSemaphore.availablePermits(), is(0)); assertThat(interrupted.get(), is(true)); } finally { service.shutdown(); } }
@Test public void testFaultsDoNotGetToEvictionAdvisor() throws StoreAccessException { final Semaphore semaphore = new Semaphore(0); final OnHeapStoreForTests<String, String> store = newStore(SystemTimeSource.INSTANCE, noAdvice()); ExecutorService executor = Executors.newCachedThreadPool(); try { executor.submit(() -> store.getOrComputeIfAbsent("prime", key -> { semaphore.acquireUninterruptibly(); return new OnHeapValueHolder<String>(0, 0, false) { @Override public String get() { return key; } }; })); while (!semaphore.hasQueuedThreads()); store.put("boom", "boom"); } finally { semaphore.release(1); executor.shutdown(); } }
@Test public void eachRequestThreadEnvironmentIsConfinedToItsThread() { Semaphore thread1Permit = new Semaphore(0); Semaphore thread2Permit = new Semaphore(0); Callable<Void> request1Task = () -> processRequest("thread 1", thread1Permit, thread2Permit); Callable<Void> request2Task = () -> processRequest("thread 2", thread2Permit, thread1Permit); runConcurrently.setTimeout(Duration.ofMinutes(1)); runConcurrently.add(request1Task); runConcurrently.add(request2Task); thread1Permit.release(); runConcurrently.executeInParallel(); }
@Test public void verifyLogcatListenerCanBeAssigned() { final Semaphore messageSemaphore = new Semaphore(1); final Duration timeout = Duration.ofSeconds(15); driver.addLogcatMessagesListener((msg) -> messageSemaphore.release()); driver.addLogcatConnectionListener(() -> System.out.println("Connected to the web socket")); driver.addLogcatDisconnectionListener(() -> System.out.println("Disconnected from the web socket")); driver.addLogcatErrorsListener(Throwable::printStackTrace); try { driver.startLogcatBroadcast(); messageSemaphore.acquire(); // This is needed for pushing some internal log messages driver.runAppInBackground(Duration.ofSeconds(1)); assertTrue(String.format("Didn't receive any log message after %s timeout", DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)), messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { throw new IllegalStateException(e); } finally { messageSemaphore.release(); driver.stopLogcatBroadcast(); } } }
/** * */ private void acquireRemapSemaphore() throws IgniteInterruptedCheckedException { try { if (remapSem.availablePermits() != REMAP_SEMAPHORE_PERMISSIONS_COUNT) { if (timeout == DFLT_UNLIMIT_TIMEOUT) { // Wait until failed data being processed. remapSem.acquire(REMAP_SEMAPHORE_PERMISSIONS_COUNT); remapSem.release(REMAP_SEMAPHORE_PERMISSIONS_COUNT); } else { // Wait until failed data being processed. boolean res = remapSem.tryAcquire(REMAP_SEMAPHORE_PERMISSIONS_COUNT, timeout, TimeUnit.MILLISECONDS); if (res) remapSem.release(REMAP_SEMAPHORE_PERMISSIONS_COUNT); else throw new IgniteDataStreamerTimeoutException("Data streamer exceeded timeout " + "while was waiting for failed data resending finished."); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IgniteInterruptedCheckedException(e); } }
@Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { if (readerSemaphore.tryAcquire(time, unit)) { int oldNumReaders = numReaders; numReaders++; if (numReaders == 1) { if (writerSemaphore.tryAcquire(time, unit)) { readerSemaphore.release(); return true; } else { numReaders = oldNumReaders; readerSemaphore.release(); return false; } } else { readerSemaphore.release(); return true; } } return false; }
public void addCall(final FSTRunnable toRun) throws InterruptedException { gateway.acquire(); if (jobs[curIdx] == null) { jobs[curIdx] = toRun; } else { jobs[curIdx].sem.acquire(); jobs[curIdx].sem.release(); jobs[curIdx] = toRun; } toRun.sem = sems[curIdx]; toRun.sem.acquire(); OrderedRunnable ord = orderedRunnableCache[curIdx]; ord.toRun = toRun; curIdx = (curIdx + 1) % threads; orderedPool.execute(ord); pool.execute(toRun); }
@Test public void testRunningJobIsInterruptedAfterShutdownNow() throws InterruptedException { BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); ExecutorService service = Executors.newSingleThreadExecutor(); try { PartitionedOrderedExecutor executor = new PartitionedOrderedExecutor(queue, service); final Semaphore jobSemaphore = new Semaphore(0); final Semaphore testSemaphore = new Semaphore(0); final AtomicBoolean interrupted = new AtomicBoolean(); executor.submit(() -> { testSemaphore.release(); try { jobSemaphore.acquire(); } catch (InterruptedException e) { interrupted.set(true); } }); testSemaphore.acquireUninterruptibly(); assertThat(executor.shutdownNow(), empty()); assertThat(executor.awaitTermination(2, MINUTES), is(true)); assertThat(executor.isShutdown(), is(true)); assertThat(executor.isTerminated(), is(true)); assertThat(jobSemaphore.availablePermits(), is(0)); assertThat(interrupted.get(), is(true)); } finally { service.shutdown(); } }
public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); Semaphore semaphore = new Semaphore(3); Runnable r = () -> { try { System.out.println("Trying to acquire - " + Thread.currentThread().getName()); if (semaphore.tryAcquire(2, TimeUnit.SECONDS)) { // use-get resource // simulate work in progress System.out.println("Acquired - " + Thread.currentThread().getName()); Thread.sleep(2000); System.out.println("Done - " + Thread.currentThread().getName()); } } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } }; for (int i = 0; i < 4; i++) { executor.execute(r); } executor.shutdown(); } }
@Test public void testQueuedJobIsStoppedAfterShutdownNow() throws InterruptedException { BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); ExecutorService service = Executors.newSingleThreadExecutor(); try { PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, 1); final Semaphore jobSemaphore = new Semaphore(0); final Semaphore testSemaphore = new Semaphore(0); executor.submit(() -> { testSemaphore.release(); jobSemaphore.acquireUninterruptibly(); }); final AtomicBoolean called = new AtomicBoolean(); executor.submit(() -> called.set(true)); testSemaphore.acquireUninterruptibly(); assertThat(executor.shutdownNow(), hasSize(1)); assertThat(executor.awaitTermination(100, MILLISECONDS), is(false)); assertThat(executor.isShutdown(), is(true)); assertThat(executor.isTerminated(), is(false)); jobSemaphore.release(); assertThat(executor.awaitTermination(2, MINUTES), is(true)); assertThat(executor.isShutdown(), is(true)); assertThat(executor.isTerminated(), is(true)); assertThat(jobSemaphore.availablePermits(), is(0)); assertThat(called.get(), is(false)); } finally { service.shutdown(); } }
@Test public void testShutdownButNonTerminatedExecutorRejectsJob() throws InterruptedException { BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); ExecutorService service = Executors.newSingleThreadExecutor(); try { PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, 1); final Semaphore semaphore = new Semaphore(0); executor.execute(semaphore::acquireUninterruptibly); executor.shutdown(); try { executor.execute(() -> { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }); fail("Expected RejectedExecutionException"); } catch (RejectedExecutionException e) { //expected } semaphore.release(); assertThat(executor.awaitTermination(2, MINUTES), is(true)); } finally { service.shutdown(); } }
@Test public void verifySyslogListenerCanBeAssigned() { final Semaphore messageSemaphore = new Semaphore(1); final Duration timeout = Duration.ofSeconds(15); driver.addSyslogMessagesListener((msg) -> messageSemaphore.release()); driver.addSyslogConnectionListener(() -> System.out.println("Connected to the web socket")); driver.addSyslogDisconnectionListener(() -> System.out.println("Disconnected from the web socket")); driver.addSyslogErrorsListener(Throwable::printStackTrace); try { driver.startSyslogBroadcast(); messageSemaphore.acquire(); // This is needed for pushing some internal log messages driver.runAppInBackground(Duration.ofSeconds(1)); assertTrue(String.format("Didn't receive any log message after %s timeout", DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)), messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { throw new IllegalStateException(e); } finally { messageSemaphore.release(); driver.stopSyslogBroadcast(); } } }
case 0: LOG.info("First peer, do nothing, just join"); if(finish0.tryAcquire(1000, java.util.concurrent.TimeUnit.MILLISECONDS)){ LOG.info("Second entering case"); if(round[1] != 0){ finish0.release(); flag = false; } else { finish3.acquire(); start0.release(); flag = false; round[2] = 1; finish3.release(); LOG.info("Third leaving"); break;
@Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (unit == null) { throw new NullPointerException("unit"); } if (inEventLoop()) { throw new IllegalStateException("cannot await termination of the current thread"); } if (threadLock.tryAcquire(timeout, unit)) { threadLock.release(); } return isTerminated(); }