Java Code Examples for net.jodah.concurrentunit.Waiter#await()

The following examples show how to use net.jodah.concurrentunit.Waiter#await() . 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: DelegatingSchedulerTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that ForkJoinPool clears interrupt flags.
 */
public void shouldClearInterruptFlagInForkJoinPoolThreads() throws Throwable {
  Scheduler scheduler = new DelegatingScheduler(new ForkJoinPool(1));
  AtomicReference<Thread> threadRef = new AtomicReference<>();
  Waiter waiter = new Waiter();

  // Create interruptable execution
  scheduler.schedule(() -> {
    threadRef.set(Thread.currentThread());
    waiter.resume();
    Thread.sleep(10000);
    return null;
  }, 0, TimeUnit.MILLISECONDS);
  waiter.await(1000);
  threadRef.get().interrupt();

  // Check for interrupt flag
  scheduler.schedule(() -> {
    waiter.assertFalse(Thread.currentThread().isInterrupted());
    waiter.resume();
    return null;
  }, 0, TimeUnit.MILLISECONDS);
  waiter.await(1000);
}
 
Example 2
Source File: MultiThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void testDisallowConcurrent() throws Exception {
    JobDetail job1 = createJob(SingletonSleepJob.class, "job1", "group1");
    CronTrigger trigger1 = createCronTrigger("trigger1", "group1", "* * * * * ?");
    CronTrigger trigger2 = createCronTrigger("trigger2", "group2", "* * * * * ?")
            .getTriggerBuilder()
            .forJob(job1)
            .build();

    Waiter waiter = new Waiter();
    scheduler.getListenerManager().addTriggerListener(new CompleteListener(waiter), NameMatcher.triggerNameEquals(trigger1.getKey().getName()));
    scheduler.scheduleJob(job1, trigger1);
    //scheduler.scheduleJob(trigger2);

    waiter.await(6000, 2);

    assertThat(SingletonSleepJob.concurrentExecutions.get(), equalTo(0));
}
 
Example 3
Source File: ReentrantCircuitTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldNotBlockOpenWhenSyncAcquired() throws Throwable {
  circuit.open();

  final Waiter waiter = new Waiter();
  new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        circuit.await();
        waiter.resume();
      } catch (InterruptedException e) {
      }
    }
  }).start();

  Thread.sleep(300);
  circuit.open();
  circuit.close();
  waiter.await(500);
}
 
Example 4
Source File: ReentrantCircuitTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldInterruptWaiters() throws Throwable {
  circuit.open();

  final Waiter waiter = new Waiter();
  for (int i = 0; i < 3; i++)
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          circuit.await();
        } catch (InterruptedException e) {
          waiter.resume();
        }
      }
    }).start();

  Thread.sleep(300);
  circuit.interruptWaiters();
  waiter.await(500);
}
 
Example 5
Source File: SingleThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void testMisfireListener() throws Exception {
    final String jobName = "oneJob";
    JobDetail jobDetail = createJob(TestJob.class, jobName, "oneGroup");

    final String triggerName = "trigger1";
    final String everySecond = "* * * * * ?";
    CronTrigger trigger = createCronTrigger(triggerName, "oneGroup", everySecond);


    JobDetail sleepJob = createJob(SleepJob.class, "sleepJob", "twoGroup");
    CronTrigger sleepTrigger = createCronTrigger("sleepTrigger", "twoGroup", everySecond);
    Waiter waiter = new Waiter();
    scheduler.scheduleJob(sleepJob, sleepTrigger);
    scheduler.scheduleJob(jobDetail, trigger);

    scheduler.getListenerManager().addTriggerListener(new MisfireListener(waiter), NameMatcher.triggerNameEquals(triggerName));

    // wait for MisfireListener.triggerMisfired() to be called
    waiter.await(2500);
}
 
Example 6
Source File: PythonInterpreterTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testPythonProcessKilled() throws InterruptedException, TimeoutException {
  final Waiter waiter = new Waiter();
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        InterpreterResult result = interpreter.interpret("import time\ntime.sleep(1000)",
                getInterpreterContext());
        waiter.assertEquals(InterpreterResult.Code.ERROR, result.code());
        waiter.assertEquals(
                "Python process is abnormally exited, please check your code and log.",
                result.message().get(0).getData());
      } catch (InterpreterException e) {
        waiter.fail("Should not throw exception\n" + ExceptionUtils.getStackTrace(e));
      }
      waiter.resume();
    }
  };
  thread.start();
  Thread.sleep(3000);
  PythonInterpreter pythonInterpreter = (PythonInterpreter)
          ((LazyOpenInterpreter) interpreter).getInnerInterpreter();
  pythonInterpreter.getPythonProcessLauncher().stop();
  waiter.await(3000);
}
 
Example 7
Source File: IPythonInterpreterTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testIPythonProcessKilled() throws InterruptedException, TimeoutException {
  final Waiter waiter = new Waiter();
  Thread thread = new Thread() {
    @Override
    public void run() {
      try {
        InterpreterResult result = interpreter.interpret("import time\ntime.sleep(1000)",
                getInterpreterContext());
        waiter.assertEquals(InterpreterResult.Code.ERROR, result.code());
        waiter.assertEquals(
                "IPython kernel is abnormally exited, please check your code and log.",
                result.message().get(0).getData());
      } catch (InterpreterException e) {
        waiter.fail("Should not throw exception\n" + ExceptionUtils.getStackTrace(e));
      }
      waiter.resume();
    }
  };
  thread.start();
  Thread.sleep(3000);
  IPythonInterpreter iPythonInterpreter = (IPythonInterpreter)
          ((LazyOpenInterpreter) interpreter).getInnerInterpreter();
  iPythonInterpreter.getKernelProcessLauncher().stop();
  waiter.await(3000);
}
 
Example 8
Source File: InterruptableWaiterTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldInterruptTimedWaiters() throws Throwable {
  final InterruptableWaiter iw = new InterruptableWaiter();
  final Waiter waiter = new Waiter();
  
  for (int i = 0; i < 3; i++)
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          iw.await(Duration.mins(1));
        } catch (InterruptedException expected) {
          waiter.resume();
        }
      }
    }).start();

  Thread.sleep(100);
  iw.interruptWaiters();
  waiter.await(500);
}
 
Example 9
Source File: FailsafeFutureTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that retries are stopped and completion handlers are called on cancel.
 */
public void shouldCallOnCompleteWhenCancelled() throws Throwable {
  Waiter waiter = new Waiter();
  CompletableFuture<String> future = Failsafe.with(new RetryPolicy<String>()).with(executor).onComplete(e -> {
    waiter.assertNull(e.getResult());
    waiter.assertTrue(e.getFailure() instanceof CancellationException);
    waiter.resume();
  }).getAsync(() -> {
    Thread.sleep(1000);
    throw new IllegalStateException();
  });

  // Note: We have to add whenComplete to the returned future separately, otherwise cancel will not be noticed by
  // Failsafe
  future.whenComplete((result, failure) -> {
    waiter.assertNull(result);
    waiter.assertTrue(failure instanceof CancellationException);
    waiter.resume();
  });

  future.cancel(true);
  waiter.await(1000, 2);
  future.complete("unxpected2");
  Asserts.assertThrows(future::get, CancellationException.class);
}
 
Example 10
Source File: DelegatingSchedulerTest.java    From failsafe with Apache License 2.0 6 votes vote down vote up
public void shouldNotInterruptAlreadyDoneTask() throws Throwable {
  Waiter waiter = new Waiter();
  Future<?> future1 = scheduler.schedule(() -> null, 0, TimeUnit.MILLISECONDS);
  Future<?> future2 = scheduler.schedule(() -> {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      waiter.fail("Cancelling one future should not interrupt another");
    }
    waiter.resume();
    return null;
  }, 0, TimeUnit.MILLISECONDS);
  Thread.sleep(100);
  assertFalse(future1.cancel(true));
  waiter.await(1000);
}
 
Example 11
Source File: ChannelClosureTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
private void performInvocation(final ShutdownSignalException e, final Waiter waiter)
    throws Throwable {
  mockConnection();
  mockInvocation(e);
  closeChannelAfterDelay();

  runInThread(new Runnable() {
    public void run() {
      try {
        mockChannel(1).proxy.basicCancel("foo-tag");
        waiter.fail("Invocation should have thrown an exception");
      } catch (Exception expected) {
        waiter.assertEquals(e, expected);
        waiter.resume();
      }
    }
  });

  waiter.await(100000);
}
 
Example 12
Source File: Issue5Test.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that a failure is handled as expected by a listener registered via whenFailure.
 */
public void test() throws Throwable {
  Waiter waiter = new Waiter();
  RetryPolicy<Object> retryPolicy = new RetryPolicy<>().withDelay(Duration.ofMillis(100))
      .withMaxDuration(Duration.ofSeconds(2))
      .withMaxRetries(3)
      .handleResult(null);

  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  Failsafe.with(retryPolicy).with(executor).onFailure(e -> {
    waiter.assertNull(e.getResult());
    waiter.assertNull(e.getFailure());
    waiter.resume();
  }).getAsync(() -> null);

  waiter.await(1000);
}
 
Example 13
Source File: Issue131Test.java    From failsafe with Apache License 2.0 6 votes vote down vote up
/**
 * More alarming async case where the Future is not even completed
 * since Failsafe does not recover from the {@link NullPointerException} thrown by the predicate.
 */
public void asyncShouldCompleteTheFuture() throws Throwable {
  CircuitBreaker<String> circuitBreaker = new CircuitBreaker<String>().handleResultIf(handleIfEqualsIgnoreCaseFoo);
  FailsafeExecutor<String> failsafe = Failsafe.with(circuitBreaker).with(Executors.newSingleThreadScheduledExecutor());

  Waiter waiter = new Waiter();

  failsafe
    .getStageAsync(() -> {
      CompletableFuture<String> future = new CompletableFuture<>();
      future.completeExceptionally(new IOException("let's blame it on network error"));
      return future;
    })
    .whenComplete((s, t) -> waiter.resume()); // Never invoked!

  waiter.await(1000);
}
 
Example 14
Source File: ReentrantCircuitTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
public void shouldHandleSequentialWaiters() throws Throwable {
  final Waiter waiter = new Waiter();
  for (int i = 0; i < 1; i++) {
    circuit.open();

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          System.out.println("Waiting for circuit to be closed");
          circuit.await();
          System.out.println("Circuit closed");
          waiter.resume();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }).start();

    Thread.sleep(500);
    circuit.close();
    waiter.await(500);
  }
}
 
Example 15
Source File: ConnectionClosureTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
private void performInvocation(final ShutdownSignalException e, final Waiter waiter)
    throws Throwable {
  mockConnection();
  mockInvocation(e);
  closeConnectionAfterDelay();

  runInThread(new Runnable() {
    public void run() {
      try {
        connectionProxy.createChannel();
        waiter.fail("Invocation should have thrown an exception");
      } catch (Exception actual) {
        if (!actual.equals(e))
          actual.printStackTrace();
        waiter.assertEquals(actual, e);
        waiter.resume();
      }
    }
  });

  waiter.await(10000);
}
 
Example 16
Source File: ConnectHandlerTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 5_000)
public void test_client_takeover_mqtt3() throws Exception {

    final CountDownLatch disconnectEventLatch = new CountDownLatch(1);
    final Waiter disconnectMessageWaiter = new Waiter();
    final TestDisconnectHandler testDisconnectHandler = new TestDisconnectHandler(disconnectMessageWaiter, false);

    final EmbeddedChannel oldChannel =
            new EmbeddedChannel(testDisconnectHandler, new TestDisconnectEventHandler(disconnectEventLatch));
    oldChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv3_1_1);
    final SettableFuture<Void> disconnectFuture = SettableFuture.create();
    disconnectFuture.set(null);
    oldChannel.attr(ChannelAttributes.DISCONNECT_FUTURE).set(disconnectFuture);

    final AtomicReference<Channel> oldChannelRef = new AtomicReference<>(oldChannel);
    when(channelPersistence.get(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.get());
    when(channelPersistence.remove(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.getAndSet(null));

    assertTrue(oldChannel.isOpen());
    assertTrue(embeddedChannel.isOpen());

    final CONNECT connect1 = new CONNECT.Mqtt3Builder().withProtocolVersion(ProtocolVersion.MQTTv3_1_1)
            .withClientIdentifier("sameClientId")
            .build();

    embeddedChannel.writeInbound(connect1);

    assertTrue(embeddedChannel.isOpen());
    assertFalse(oldChannel.isOpen());
    assertTrue(oldChannel.attr(ChannelAttributes.TAKEN_OVER).get());

    assertTrue(disconnectEventLatch.await(5, TimeUnit.SECONDS));
    disconnectMessageWaiter.await();

    final DISCONNECT disconnectMessage = testDisconnectHandler.getDisconnectMessage();
    assertNull(disconnectMessage);
}
 
Example 17
Source File: ChannelInvocationTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that concurrent failed invocations result in recovery being performed serially.
 * 
 * TODO rewrite this test since concurrent failures no longer result in concurrent recovery
 * attempts. A ShutdownListener is only called once per recovery attempt.
 */
@Test(enabled = false)
public void shouldHandleConcurrentRetryableFailures() throws Throwable {
  mockConnection();
  mockConsumer(1, 1);
  mockConsumer(1, 2);
  mockConsumer(2, 5);
  mockConsumer(2, 6);

  doAnswer(failNTimes(4, retryableChannelShutdownSignal(), null, mockChannel(1).channelHandler)).when(
      mockChannel(1).delegate)
      .basicCancel("foo-tag");

  final Waiter waiter = new Waiter();
  for (int i = 0; i < 2; i++)
    runInThread(new Runnable() {
      public void run() {
        try {
          performInvocation();
          waiter.resume();
        } catch (Throwable t) {
          waiter.fail(t);
        }
      }
    });

  waiter.await(2000);

  // Even though both threads will fail twice, only one thread will perform recovery
  verifyCxnCreations(1);
  verifyChannelCreations(1, 3);
  verifyChannelCreations(2, 1);
  verifyConsumerCreations(1, 1, 3);
  verifyConsumerCreations(1, 2, 3);
  verifyConsumerCreations(2, 5, 1);
  verifyConsumerCreations(2, 6, 1);
  // Initial failure plus two retries for each thread
  verifyInvocations(6);
}
 
Example 18
Source File: SingleThreadedIntegrationTest.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleExecution() throws Exception {
    final String jobName = "oneJob";
    JobDetail jobDetail = createJob(TestJob.class, jobName, "oneGroup");

    SimpleTrigger trigger = TriggerBuilder.newTrigger().withSchedule(simpleSchedule().withRepeatCount(0).withIntervalInMilliseconds(200)).build();

    Waiter waiter = new Waiter();
    scheduler.getListenerManager().addTriggerListener(new CompleteListener(waiter), NameMatcher.triggerNameEquals(trigger.getKey().getName()));

    scheduler.scheduleJob(jobDetail, trigger);

    waiter.await(2000);
}
 
Example 19
Source File: ConnectHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_client_takeover_retry_mqtt3() throws Exception {

    final SettableFuture<Void> disconnectFuture = SettableFuture.create();

    final CountDownLatch disconnectEventLatch = new CountDownLatch(1);
    final Waiter disconnectMessageWaiter = new Waiter();
    final TestDisconnectHandler testDisconnectHandler = new TestDisconnectHandler(disconnectMessageWaiter, false);

    final EmbeddedChannel oldChannel =
            new EmbeddedChannel(testDisconnectHandler, new TestDisconnectEventHandler(disconnectEventLatch));
    oldChannel.attr(ChannelAttributes.TAKEN_OVER).set(true);
    oldChannel.attr(ChannelAttributes.DISCONNECT_FUTURE).set(disconnectFuture);
    oldChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv3_1);

    final AtomicReference<Channel> oldChannelRef = new AtomicReference<>(oldChannel);
    when(channelPersistence.get(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.get());
    when(channelPersistence.remove(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.getAndSet(null));

    assertTrue(oldChannel.isOpen());
    assertTrue(embeddedChannel.isOpen());

    final CONNECT connect1 = new CONNECT.Mqtt5Builder().withClientIdentifier("sameClientId").build();

    embeddedChannel.writeInbound(connect1);

    assertTrue(oldChannel.isOpen());
    assertTrue(embeddedChannel.isOpen());

    oldChannel.attr(ChannelAttributes.TAKEN_OVER).set(false);
    disconnectFuture.set(null);

    embeddedChannel.runPendingTasks();

    assertTrue(embeddedChannel.isOpen());
    assertFalse(oldChannel.isOpen());
    assertTrue(oldChannel.attr(ChannelAttributes.TAKEN_OVER).get());

    assertTrue(disconnectEventLatch.await(5, TimeUnit.SECONDS));
    disconnectMessageWaiter.await();

    final DISCONNECT disconnectMessage = testDisconnectHandler.getDisconnectMessage();
    assertNull(disconnectMessage);
}
 
Example 20
Source File: ConnectHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_client_takeover_retry_mqtt5() throws Exception {

    final SettableFuture<Void> disconnectFuture = SettableFuture.create();

    final CountDownLatch disconnectEventLatch = new CountDownLatch(1);
    final Waiter disconnectMessageWaiter = new Waiter();
    final TestDisconnectHandler testDisconnectHandler = new TestDisconnectHandler(disconnectMessageWaiter, true);

    final EmbeddedChannel oldChannel =
            new EmbeddedChannel(testDisconnectHandler, new TestDisconnectEventHandler(disconnectEventLatch));
    oldChannel.attr(ChannelAttributes.TAKEN_OVER).set(true);
    oldChannel.attr(ChannelAttributes.DISCONNECT_FUTURE).set(disconnectFuture);
    oldChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv5);

    final AtomicReference<Channel> oldChannelRef = new AtomicReference<>(oldChannel);
    when(channelPersistence.get(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.get());
    when(channelPersistence.remove(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.getAndSet(null));

    assertTrue(oldChannel.isOpen());
    assertTrue(embeddedChannel.isOpen());

    final CONNECT connect1 = new CONNECT.Mqtt5Builder().withClientIdentifier("sameClientId").build();

    embeddedChannel.writeInbound(connect1);

    assertTrue(oldChannel.isOpen());
    assertTrue(embeddedChannel.isOpen());

    oldChannel.attr(ChannelAttributes.TAKEN_OVER).set(false);
    disconnectFuture.set(null);

    embeddedChannel.runPendingTasks();

    assertTrue(embeddedChannel.isOpen());
    assertFalse(oldChannel.isOpen());
    assertTrue(oldChannel.attr(ChannelAttributes.TAKEN_OVER).get());

    assertTrue(disconnectEventLatch.await(5, TimeUnit.SECONDS));
    disconnectMessageWaiter.await();

    final DISCONNECT disconnectMessage = testDisconnectHandler.getDisconnectMessage();
    assertNotNull(disconnectMessage);
    assertEquals(Mqtt5DisconnectReasonCode.SESSION_TAKEN_OVER, disconnectMessage.getReasonCode());
    assertEquals(ReasonStrings.DISCONNECT_SESSION_TAKEN_OVER, disconnectMessage.getReasonString());
}