Java Code Examples for java.util.concurrent.Phaser#awaitAdvanceInterruptibly()

The following examples show how to use java.util.concurrent.Phaser#awaitAdvanceInterruptibly() . 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: MediumConcurrencyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
@Disabled // just a test for showing the phaser
public void testPhaser() throws Exception {

	final Phaser p1 = new Phaser(1);
	final Random rand = new Random();

	for (int i = 0; i < 10; i++) {
		final int tid = i;
		executor.submit(() -> {
			p1.register();
			try {
				Thread.sleep(rand.nextInt(10) * 1000);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			System.out.println("Task " + tid + " done");
			p1.arriveAndDeregister();
		});
	}
	System.out.println("Waiting for tasks to finish");
	p1.awaitAdvanceInterruptibly(p1.arrive(), 15, TimeUnit.SECONDS);
	System.out.println("Done");
}
 
Example 2
Source File: FluxTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void combineWithOneElement() throws InterruptedException, TimeoutException {
	AtomicReference<Object> ref = new AtomicReference<>(null);

	Phaser phaser = new Phaser(2);

	Flux<Object> s1 = Processors.more().replayLatestOrDefault(new Object())
	                                 .publishOn(asyncGroup);
	Flux<Object> s2 = Processors.more().replayLatestOrDefault(new Object())
	                                .publishOn(asyncGroup);

	// The following works:
	//List<Flux<Object>> list = Arrays.collectList(s1);
	// The following fails:
	List<Flux<Object>> list = Arrays.asList(s1, s2);

	Flux.combineLatest(list, t -> t)
	       .log()
	       .doOnNext(obj -> {
		       ref.set(obj);
		       phaser.arrive();
	       })
	       .subscribe();

	phaser.awaitAdvanceInterruptibly(phaser.arrive(), 1, TimeUnit.SECONDS);
	Assert.assertNotNull(ref.get());
}
 
Example 3
Source File: FluxTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * This test case demonstrates a silent failure of {@link Flux#interval(Duration)}
 * when a resolution is specified that
 * is less than the backing {@link Timer} class.
 *
 * @throws InterruptedException - on failure.
 * @throws TimeoutException     - on failure. <p> by @masterav10 : https://github.com/reactor/reactor/issues/469
 */
@Test
@Ignore
public void endLessTimer() throws InterruptedException, TimeoutException {
	int tasks = 50;
	long delayMS = 50; // XXX: Fails when less than 100
	Phaser barrier = new Phaser(tasks + 1);

	List<Long> times = new ArrayList<>();

	// long localTime = System.currentTimeMillis(); for java 7
	long localTime = Instant.now()
	                        .toEpochMilli();
	long elapsed = System.nanoTime();

	Disposable ctrl = Flux.interval(Duration.ofMillis(delayMS))
	                      .log("test")
	                      .map((signal) -> {
		                      return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - elapsed);
	                      })
	                      .doOnNext((elapsedMillis) -> {
		                      times.add(localTime + elapsedMillis);
		                      barrier.arrive();
	                      })
	                      .subscribe();

	barrier.awaitAdvanceInterruptibly(barrier.arrive(), tasks * delayMS + 1000, TimeUnit.MILLISECONDS);
	ctrl.dispose();

	Assert.assertEquals(tasks, times.size());

	for (int i = 1; i < times.size(); i++) {
		Long prev = times.get(i - 1);
		Long time = times.get(i);

		Assert.assertTrue(prev > 0);
		Assert.assertTrue(time > 0);
		Assert.assertTrue("was " + (time - prev), time - prev <= delayMS * 1.2);
	}
}
 
Example 4
Source File: DataTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public void serverIncrementOverwritesExistingData(boolean online)
    throws DatabaseException, TimeoutException, InterruptedException {
  DatabaseConfig cfg = IntegrationTestHelpers.newTestConfig();
  DatabaseReference ref = IntegrationTestHelpers.rootWithConfig(cfg);
  List<Object> foundValues = new ArrayList<>();
  // Note: all numeric values will be long, so they must be cast before being inserted.
  List<Object> expectedValues = new ArrayList<>();

  // Going offline ensures that local events get queued up before server events
  if (!online) {
    IntegrationTestHelpers.goOffline(cfg);
  }

  // Phaser is the closest built-in to a bidrectional latch. We could use a semaphore with a fixed
  // number of permits, but the test would be fragile since the permit count isn't closely related
  // to the test cases.
  final Phaser latch = new Phaser(0);

  ValueEventListener listener =
      ref.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              foundValues.add(snapshot.getValue());
              latch.arrive();
            }

            @Override
            public void onCancelled(DatabaseError error) {}
          });

  try {
    // null + incr
    latch.register();
    ref.setValue(ServerValue.increment(1));
    expectedValues.add((long) 1);

    // number + incr
    latch.bulkRegister(2);
    ref.setValue(5);
    ref.setValue(ServerValue.increment(1));
    expectedValues.add((long) 5);
    expectedValues.add((long) 6);

    // string + incr
    latch.bulkRegister(2);
    ref.setValue("hello");
    ref.setValue(ServerValue.increment(1));
    expectedValues.add("hello");
    expectedValues.add((long) 1);

    // object + incr
    latch.bulkRegister(2);
    Map<String, Object> obj = new MapBuilder().put("hello", "world").build();
    ref.setValue(obj);
    ref.setValue(ServerValue.increment(1));
    expectedValues.add(obj);
    expectedValues.add((long) 1);

    latch.awaitAdvanceInterruptibly(0, IntegrationTestValues.getTimeout(), MILLISECONDS);
    assertEquals(expectedValues, foundValues);
  } finally {
    ref.removeEventListener(listener);
    if (!online) {
      IntegrationTestHelpers.goOnline(cfg);
    }
  }
}
 
Example 5
Source File: DataTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public void serverIncrementPriority(boolean online)
    throws DatabaseException, TimeoutException, InterruptedException {
  DatabaseConfig cfg = IntegrationTestHelpers.newTestConfig();
  DatabaseReference ref = IntegrationTestHelpers.rootWithConfig(cfg);
  List<Object> foundPriorities = new ArrayList<>();
  // Note: all numeric values will be long or double, so they must be cast before being inserted.
  List<Object> expectedPriorities = new ArrayList<>();

  // Going offline ensures that local events get queued up before server events
  if (!online) {
    IntegrationTestHelpers.goOffline(cfg);
  }

  // Phaser is the closest built-in to a bidrectional latch. We could use a semaphore with a fixed
  // number of permits, but the test would be fragile since the permit count isn't closely related
  // to the test cases.
  final Phaser latch = new Phaser(0);

  ValueEventListener listener =
      ref.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              foundPriorities.add(snapshot.getPriority());
              latch.arrive();
            }

            @Override
            public void onCancelled(DatabaseError error) {}
          });

  try {
    // null + increment
    latch.register();
    ref.setValue(0, ServerValue.increment(1));
    // numeric priorities are always doubles
    expectedPriorities.add(1.0);

    // long + double
    latch.register();
    ref.setValue(0, ServerValue.increment(1.5));
    expectedPriorities.add(2.5);

    // Checking types first makes failures much more obvious
    latch.awaitAdvanceInterruptibly(0, IntegrationTestValues.getTimeout(), MILLISECONDS);
    assertEquals(expectedPriorities, foundPriorities);
  } finally {
    ref.removeEventListener(listener);
    if (!online) {
      IntegrationTestHelpers.goOnline(cfg);
    }
  }
}
 
Example 6
Source File: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the ManagedExecutor implementation starts 2 async tasks/actions, and no more,
 * when maxAsync is configured to 2.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void maxAsync2() throws ExecutionException, InterruptedException, TimeoutException {
    ManagedExecutor executor = ManagedExecutor.builder()
            .maxAsync(2)
            .propagated()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Phaser barrier = new Phaser(2);
    try {
        // Use up both maxAsync slots on blocking operations and wait for them to start
        Future<Integer> future1 = executor.submit(() -> barrier.awaitAdvance(barrier.arriveAndAwaitAdvance()));
        CompletableFuture<Integer> future2 = executor.supplyAsync(() -> barrier.awaitAdvance(barrier.arriveAndAwaitAdvance()));
        barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);

        // This data structure holds the results of tasks which shouldn't be able to run yet
        LinkedBlockingQueue<String> results = new LinkedBlockingQueue<String>();

        // Submit additional tasks/actions for async execution.
        // These should queue, but otherwise be unable to start yet due to maxAsync=2.
        CompletableFuture<Void> future3 = executor.runAsync(() -> results.offer("Result3"));
        CompletableFuture<Boolean> future4 = executor.supplyAsync(() -> results.offer("Result4"));
        Future<Boolean> future5 = executor.submit(() -> results.offer("Result5"));
        CompletableFuture<Boolean> future6 = executor.completedFuture("6")
                .thenApplyAsync(s -> results.offer("Result" + s));

        // Detect whether any of the above tasks/actions run within the next 5 seconds
        Assert.assertNull(results.poll(5, TimeUnit.SECONDS),
                "Should not be able start more than 2 async tasks when maxAsync is 2.");

        // unblock and allow tasks to finish
        barrier.arrive();
        barrier.arrive(); // there are 2 parties in each phase

        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "None of the queued tasks ran.");
        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "Only 1 of the queued tasks ran.");
        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "Only 2 of the queued tasks ran.");
        Assert.assertNotNull(results.poll(MAX_WAIT_NS, TimeUnit.SECONDS), "Only 3 of the queued tasks ran.");

        Assert.assertEquals(future1.get(), Integer.valueOf(2), "Unexpected result of first task.");
        Assert.assertEquals(future2.get(), Integer.valueOf(2), "Unexpected result of second task.");
        Assert.assertNull(future3.join(), "Unexpected result of third task.");
        Assert.assertEquals(future4.join(), Boolean.TRUE, "Unexpected result of fourth task.");
        Assert.assertEquals(future5.get(), Boolean.TRUE, "Unexpected result of fifth task.");
        Assert.assertEquals(future6.get(), Boolean.TRUE, "Unexpected result of sixth task.");
    }
    finally {
        barrier.forceTermination();
        executor.shutdownNow();
    }
}
 
Example 7
Source File: MPConfigTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that the maxAsync and maxQueued attributes of a ManagedExecutor are defaulted
 * according to the defaults specified by the application in MicroProfile Config.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test(dependsOnMethods = "beanInjected")
public void defaultMaxAsyncAndMaxQueuedForManagedExecutorViaMPConfig()
        throws ExecutionException, InterruptedException, TimeoutException {

    // Expected config is maxAsync=1, maxQueued=4; propagated=Buffer; cleared=Remaining
    ManagedExecutor executor = ManagedExecutor.builder().propagated(Buffer.CONTEXT_NAME).build();

    Phaser barrier = new Phaser(1);
    try {
        // Set non-default values
        Buffer.set(new StringBuffer("defaultMaxAsyncAndMaxQueuedForManagedExecutorViaMPConfig-test-buffer"));
        Label.set("defaultMaxAsyncAndMaxQueuedForManagedExecutorViaMPConfig-test-label");

        // First, use up the single maxAsync slot with a blocking task and wait for it to start
        executor.submit(() -> barrier.awaitAdvanceInterruptibly(barrier.arrive() + 1));
        barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);

        // Use up queue positions
        CompletableFuture<String> cf1 = executor.supplyAsync(() -> Buffer.get().toString());
        CompletableFuture<String> cf2 = executor.supplyAsync(() -> Label.get());
        CompletableFuture<String> cf3 = executor.supplyAsync(() -> "III");
        CompletableFuture<String> cf4 = executor.supplyAsync(() -> "IV");

        // Fifth attempt to queue a task must be rejected
        try {
            CompletableFuture<String> cf5 = executor.supplyAsync(() -> "V");
            // CompletableFuture interface does not provide detail on precisely how to report rejection,
            // so tolerate both possibilities: exception raised or stage returned with exceptional completion.   
            Assert.assertTrue(cf5.isDone() && cf5.isCompletedExceptionally(),
                    "Exceeded maxQueued of 4. Future for 5th queued task/action is " + cf5);
        }
        catch (RejectedExecutionException x) {
            // test passes
        }

        // unblock and allow tasks to finish
        barrier.arrive();

        Assert.assertEquals(cf1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "defaultMaxAsyncAndMaxQueuedForManagedExecutorViaMPConfig-test-buffer",
                "First task: Context not propagated as configured on the builder.");

        Assert.assertEquals(cf2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "",
                "Second task: Context not cleared as defaulted by MicroProfile Config property.");

        Assert.assertEquals(cf3.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "III",
                "Unexpected result of third task.");

        Assert.assertEquals(cf4.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "IV",
                "Unexpected result of fourth task.");
    }
    finally {
        barrier.forceTermination();

        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example 8
Source File: MPConfigTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that MicroProfile config defaults the maxAsync attribute and honors the explicitly specified
 * maxQueued attribute, when only the propagated and maxQueued attributes are specified by the application.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test(dependsOnMethods = "beanInjected")
public void explicitlySpecifyMaxQueued5()
        throws ExecutionException, InterruptedException, TimeoutException {

    // Expected config is maxAsync=1; maxQueued=5; propagated={}; cleared=Remaining
    Assert.assertNotNull(producedExecutor, "Injection failure. Cannot run test.");

    Phaser barrier = new Phaser(1);
    try {
        // First, use up the single maxAsync slot with a blocking task and wait for it to start
        producedExecutor.submit(() -> barrier.awaitAdvanceInterruptibly(barrier.arrive() + 1));
        barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);

        // Use up queue positions
        CompletableFuture<String> future1 = producedExecutor.supplyAsync(() -> "Q_1");
        CompletableFuture<String> future2 = producedExecutor.supplyAsync(() -> "Q_2");
        CompletableFuture<String> future3 = producedExecutor.supplyAsync(() -> "Q_3");
        Future<String> future4 = producedExecutor.submit(() -> "Q_4");
        Future<String> future5 = producedExecutor.submit(() -> "Q_5");

        // Sixth attempt to queue a task must be rejected
        try {
            Future<String> future6 = producedExecutor.submit(() -> "Q_6");
            Assert.fail("Exceeded maxQueued of 5. Future for 6th queued task/action is " + future6);
        }
        catch (RejectedExecutionException x) {
            // test passes
        }

        // unblock and allow tasks to finish
        barrier.arrive();

        Assert.assertEquals(future1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_1",
                "Unexpected result of first task.");

        Assert.assertEquals(future2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_2",
                "Unexpected result of second task.");

        Assert.assertEquals(future3.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_3",
                "Unexpected result of third task.");

        Assert.assertEquals(future4.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_4",
                "Unexpected result of fourth task.");

        Assert.assertEquals(future5.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_5",
                "Unexpected result of fifth task.");
    }
    finally {
        barrier.forceTermination();
    } 
}
 
Example 9
Source File: ProcessTools.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Starts a process from its builder.</p>
 * <span>The default redirects of STDOUT and STDERR are started</span>
 * <p>
 * It is possible to wait for the process to get to a warmed-up state
 * via {@linkplain Predicate} condition on the STDOUT
 * </p>
 * @param name The process name
 * @param processBuilder The process builder
 * @param linePredicate The {@linkplain Predicate} to use on the STDOUT
 *                      Used to determine the moment the target app is
 *                      properly warmed-up.
 *                      It can be null - in that case the warmup is skipped.
 * @param timeout The timeout for the warmup waiting
 * @param unit The timeout {@linkplain TimeUnit}
 * @return Returns the initialized {@linkplain Process}
 * @throws IOException
 * @throws InterruptedException
 * @throws TimeoutException
 */
public static Process startProcess(String name,
                                   ProcessBuilder processBuilder,
                                   final Predicate<String> linePredicate,
                                   long timeout,
                                   TimeUnit unit)
throws IOException, InterruptedException, TimeoutException {
    Process p = processBuilder.start();
    StreamPumper stdout = new StreamPumper(p.getInputStream());
    StreamPumper stderr = new StreamPumper(p.getErrorStream());

    stdout.addPump(new LineForwarder(name, System.out));
    stderr.addPump(new LineForwarder(name, System.err));
    final Phaser phs = new Phaser(1);
    if (linePredicate != null) {
        stdout.addPump(new StreamPumper.LinePump() {
            @Override
            protected void processLine(String line) {
                if (linePredicate.test(line)) {
                    if (phs.getRegisteredParties() > 0) {
                        phs.arriveAndDeregister();
                    }
                }
            }
        });
    }
    Future<Void> stdoutTask = stdout.process();
    Future<Void> stderrTask = stderr.process();

    try {
        if (timeout > -1) {
            phs.awaitAdvanceInterruptibly(0, timeout, unit);
        }
    } catch (TimeoutException | InterruptedException e) {
        System.err.println("Failed to start a process (thread dump follows)");
        for(Map.Entry<Thread, StackTraceElement[]> s : Thread.getAllStackTraces().entrySet()) {
            printStack(s.getKey(), s.getValue());
        }
        stdoutTask.cancel(true);
        stderrTask.cancel(true);
        throw e;
    }

    return p;
}
 
Example 10
Source File: ProcessTools.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>Starts a process from its builder.</p>
 * <span>The default redirects of STDOUT and STDERR are started</span>
 * <p>
 * It is possible to wait for the process to get to a warmed-up state
 * via {@linkplain Predicate} condition on the STDOUT
 * </p>
 * @param name The process name
 * @param processBuilder The process builder
 * @param linePredicate The {@linkplain Predicate} to use on the STDOUT
 *                      Used to determine the moment the target app is
 *                      properly warmed-up.
 *                      It can be null - in that case the warmup is skipped.
 * @param timeout The timeout for the warmup waiting
 * @param unit The timeout {@linkplain TimeUnit}
 * @return Returns the initialized {@linkplain Process}
 * @throws IOException
 * @throws InterruptedException
 * @throws TimeoutException
 */
public static Process startProcess(String name,
                                   ProcessBuilder processBuilder,
                                   final Predicate<String> linePredicate,
                                   long timeout,
                                   TimeUnit unit)
throws IOException, InterruptedException, TimeoutException {
    Process p = processBuilder.start();
    StreamPumper stdout = new StreamPumper(p.getInputStream());
    StreamPumper stderr = new StreamPumper(p.getErrorStream());

    stdout.addPump(new LineForwarder(name, System.out));
    stderr.addPump(new LineForwarder(name, System.err));
    final Phaser phs = new Phaser(1);
    if (linePredicate != null) {
        stdout.addPump(new StreamPumper.LinePump() {
            @Override
            protected void processLine(String line) {
                if (linePredicate.test(line)) {
                    if (phs.getRegisteredParties() > 0) {
                        phs.arriveAndDeregister();
                    }
                }
            }
        });
    }
    Future<Void> stdoutTask = stdout.process();
    Future<Void> stderrTask = stderr.process();

    try {
        if (timeout > -1) {
            phs.awaitAdvanceInterruptibly(0, timeout, unit);
        }
    } catch (TimeoutException | InterruptedException e) {
        System.err.println("Failed to start a process (thread dump follows)");
        for(Map.Entry<Thread, StackTraceElement[]> s : Thread.getAllStackTraces().entrySet()) {
            printStack(s.getKey(), s.getValue());
        }
        stdoutTask.cancel(true);
        stderrTask.cancel(true);
        throw e;
    }

    return p;
}