Search in sources :

Example 1 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project neo4j by neo4j.

the class TicketedProcessingTest method shouldReturnTicketsInOrder.

@Test
public void shouldReturnTicketsInOrder() throws Exception {
    // GIVEN
    int items = 1_000;
    ParkStrategy park = new ParkStrategy.Park(2, MILLISECONDS);
    BiFunction<Integer, Void, Integer> processor = (from, ignore) -> {
        if (ThreadLocalRandom.current().nextFloat() < 0.01f) {
            park.park(Thread.currentThread());
        }
        return from * 2;
    };
    int processorCount = Runtime.getRuntime().availableProcessors();
    Future<Void> assertions;
    try (TicketedProcessing<Integer, Void, Integer> processing = new TicketedProcessing<>("Doubler", processorCount, processor, () -> null)) {
        processing.processors(processorCount - processing.processors(0));
        // WHEN
        assertions = t2.execute(new WorkerCommand<Void, Void>() {

            @Override
            public Void doWork(Void state) throws Exception {
                for (int i = 0; i < items; i++) {
                    Integer next = processing.next();
                    assertNotNull(next);
                    assertEquals(i * 2, next.intValue());
                }
                assertNull(processing.next());
                return null;
            }
        });
        for (int i = 0; i < items; i++) {
            processing.submit(i);
        }
    }
    // THEN
    assertions.get();
}
Also used : Assert.assertNotNull(org.junit.Assert.assertNotNull) BiFunction(java.util.function.BiFunction) OtherThreadRule(org.neo4j.test.rule.concurrent.OtherThreadRule) Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Integer.parseInt(java.lang.Integer.parseInt) WorkerCommand(org.neo4j.test.OtherThreadExecutor.WorkerCommand) CountDownLatch(java.util.concurrent.CountDownLatch) Future(java.util.concurrent.Future) Rule(org.junit.Rule) Assert.assertNull(org.junit.Assert.assertNull) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) DoubleLatch.awaitLatch(org.neo4j.test.DoubleLatch.awaitLatch) ParkStrategy(org.neo4j.unsafe.impl.batchimport.executor.ParkStrategy) Assert.assertEquals(org.junit.Assert.assertEquals) WorkerCommand(org.neo4j.test.OtherThreadExecutor.WorkerCommand) ParkStrategy(org.neo4j.unsafe.impl.batchimport.executor.ParkStrategy) Test(org.junit.Test)

Example 2 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project streamsupport by stefan-zobel.

the class SubmissionPublisherTest method testHandledDroppedTimedOffer.

/**
 * Timed offer invokes drop handler if saturated
 */
public void testHandledDroppedTimedOffer() {
    AtomicInteger calls = new AtomicInteger();
    SubmissionPublisher<Integer> p = new SubmissionPublisher<>(basicExecutor, 4);
    TestSubscriber s1 = new TestSubscriber();
    s1.request = false;
    TestSubscriber s2 = new TestSubscriber();
    s2.request = false;
    p.subscribe(s1);
    p.subscribe(s2);
    s2.awaitSubscribe();
    s1.awaitSubscribe();
    long delay = timeoutMillis();
    for (int i = 1; i <= 4; ++i) assertTrue(p.offer(i, delay, MILLISECONDS, (s, x) -> noopHandle(calls)) >= 0);
    long startTime = System.nanoTime();
    assertTrue(p.offer(5, delay, MILLISECONDS, (s, x) -> noopHandle(calls)) < 0);
    s1.sn.request(64);
    assertTrue(p.offer(6, delay, MILLISECONDS, (s, x) -> noopHandle(calls)) < 0);
    assertTrue(millisElapsedSince(startTime) >= delay);
    s2.sn.request(64);
    p.close();
    s2.awaitComplete();
    s1.awaitComplete();
    assertTrue(calls.get() >= 2);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(junit.framework.Test) Subscription(java8.util.concurrent.Flow.Subscription) Executor(java.util.concurrent.Executor) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Subscriber(java8.util.concurrent.Flow.Subscriber) Executors(java.util.concurrent.Executors) Flow(java8.util.concurrent.Flow) TestSuite(junit.framework.TestSuite) CountDownLatch(java.util.concurrent.CountDownLatch) CompletableFuture(java8.util.concurrent.CompletableFuture) SubmissionPublisher(java8.util.concurrent.SubmissionPublisher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ForkJoinPool(java8.util.concurrent.ForkJoinPool) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SubmissionPublisher(java8.util.concurrent.SubmissionPublisher)

Example 3 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project tutorials by eugenp.

the class MetricTypeTest method givenStatsTimer_whenExecuteTask_thenStatsCalculated.

@Test
public // ==
void givenStatsTimer_whenExecuteTask_thenStatsCalculated() throws Exception {
    System.setProperty("netflix.servo", "1000");
    StatsTimer timer = new StatsTimer(MonitorConfig.builder("test").build(), new StatsConfig.Builder().withComputeFrequencyMillis(2000).withPercentiles(new double[] { 99.0, 95.0, 90.0 }).withPublishMax(true).withPublishMin(true).withPublishCount(true).withPublishMean(true).withPublishStdDev(true).withPublishVariance(true).build(), MILLISECONDS);
    Stopwatch stopwatch = timer.start();
    MILLISECONDS.sleep(1);
    timer.record(3, MILLISECONDS);
    stopwatch.stop();
    stopwatch = timer.start();
    timer.record(6, MILLISECONDS);
    MILLISECONDS.sleep(2);
    stopwatch.stop();
    assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalTime());
    assertEquals("timer should count 12 milliseconds in total", 12, timer.getTotalMeasurement());
    assertEquals("timer should record 4 updates", 4, timer.getCount());
    assertEquals("stats timer value time-cost/update should be 2", 3, timer.getValue().intValue());
    final Map<String, Number> metricMap = timer.getMonitors().stream().collect(toMap(monitor -> getMonitorTagValue(monitor, "statistic"), monitor -> (Number) monitor.getValue()));
    assertThat(metricMap.keySet(), containsInAnyOrder("count", "totalTime", "max", "min", "variance", "stdDev", "avg", "percentile_99", "percentile_95", "percentile_90"));
}
Also used : Counter(com.netflix.servo.monitor.Counter) BucketTimer(com.netflix.servo.monitor.BucketTimer) StepCounter(com.netflix.servo.monitor.StepCounter) Monitor(com.netflix.servo.monitor.Monitor) Assert.assertThat(org.junit.Assert.assertThat) Collectors.toMap(java.util.stream.Collectors.toMap) StatsConfig(com.netflix.servo.stats.StatsConfig) BasicTimer(com.netflix.servo.monitor.BasicTimer) StatsTimer(com.netflix.servo.monitor.StatsTimer) Map(java.util.Map) BasicGauge(com.netflix.servo.monitor.BasicGauge) Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) Gauge(com.netflix.servo.monitor.Gauge) MaxGauge(com.netflix.servo.monitor.MaxGauge) Matchers.allOf(org.hamcrest.Matchers.allOf) BasicCounter(com.netflix.servo.monitor.BasicCounter) Test(org.junit.Test) PeakRateCounter(com.netflix.servo.monitor.PeakRateCounter) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Ignore(org.junit.Ignore) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) MonitorConfig(com.netflix.servo.monitor.MonitorConfig) Stopwatch(com.netflix.servo.monitor.Stopwatch) Monitors(com.netflix.servo.monitor.Monitors) BasicInformational(com.netflix.servo.monitor.BasicInformational) BucketConfig(com.netflix.servo.monitor.BucketConfig) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) StatsTimer(com.netflix.servo.monitor.StatsTimer) Stopwatch(com.netflix.servo.monitor.Stopwatch) Test(org.junit.Test)

Example 4 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project mule by mulesoft.

the class DefaultExceptionStrategyTestCase method testExceptionNotifications.

// MULE-1627
@Test
public void testExceptionNotifications() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger notificationCount = new AtomicInteger(0);
    ((MuleContextWithRegistries) muleContext).getRegistry().lookupObject(NotificationListenerRegistry.class).registerListener((ExceptionNotificationListener) notification -> {
        if (new IntegerAction(EXCEPTION_ACTION).equals(notification.getAction())) {
            assertEquals("exception", notification.getActionName());
            assertEquals("Wrong info type", TYPE_ERROR, notification.getType());
            notificationCount.incrementAndGet();
            latch.countDown();
        }
    });
    // throwing exception
    InstrumentedExceptionStrategy strategy = new InstrumentedExceptionStrategy(muleContext);
    strategy.setAnnotations(singletonMap(LOCATION_KEY, TEST_CONNECTOR_LOCATION));
    strategy.setMuleContext(muleContext);
    strategy.setNotificationFirer(((MuleContextWithRegistries) muleContext).getRegistry().lookupObject(NotificationDispatcher.class));
    strategy.handleException(new IllegalArgumentException("boom"));
    // Wait for the notifcation event to be fired as they are queue
    latch.await(2000, MILLISECONDS);
    assertEquals(1, notificationCount.get());
}
Also used : Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) NotificationListenerRegistry(org.mule.runtime.api.notification.NotificationListenerRegistry) MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) CountDownLatch(java.util.concurrent.CountDownLatch) IntegerAction(org.mule.runtime.api.notification.IntegerAction) MuleContext(org.mule.runtime.core.api.MuleContext) AbstractMuleContextTestCase(org.mule.tck.junit4.AbstractMuleContextTestCase) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TYPE_ERROR(org.mule.runtime.api.notification.AbstractServerNotification.TYPE_ERROR) Collections.singletonMap(java.util.Collections.singletonMap) EXCEPTION_ACTION(org.mule.runtime.api.notification.ExceptionNotification.EXCEPTION_ACTION) ExceptionNotificationListener(org.mule.runtime.api.notification.ExceptionNotificationListener) NotificationDispatcher(org.mule.runtime.api.notification.NotificationDispatcher) LOCATION_KEY(org.mule.runtime.api.component.AbstractComponent.LOCATION_KEY) Assert.assertEquals(org.junit.Assert.assertEquals) IntegerAction(org.mule.runtime.api.notification.IntegerAction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MuleContextWithRegistries(org.mule.runtime.core.internal.context.MuleContextWithRegistries) NotificationListenerRegistry(org.mule.runtime.api.notification.NotificationListenerRegistry) NotificationDispatcher(org.mule.runtime.api.notification.NotificationDispatcher) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 5 with MILLISECONDS

use of java.util.concurrent.TimeUnit.MILLISECONDS in project mule by mulesoft.

the class ExpiryMonitorTestCase method testExpiryWithReset.

@Test
public void testExpiryWithReset() throws InterruptedException {
    Expirable e = () -> expire();
    monitor.addExpirable(EXPIRE_TIME, MILLISECONDS, e);
    monitor.run();
    assertThat(expired, is(false));
    long startTime = currentTimeMillis();
    monitor.resetExpirable(e);
    monitor.run();
    assertTrue(!expired);
    new PollingProber(EXPIRE_TIMEOUT, 50).check(new JUnitLambdaProbe(() -> {
        assertThat(monitor.isRegistered(e), is(false));
        assertThat(expired, is(true));
        return true;
    }, ae -> {
        ae.printStackTrace();
        return "" + currentTimeMillis() + " - " + monitor.toString();
    }));
    assertThat(expiredTime - startTime, greaterThanOrEqualTo(EXPIRE_TIME - DELTA_TIME));
}
Also used : Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) System.currentTimeMillis(java.lang.System.currentTimeMillis) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Expirable(org.mule.runtime.core.privileged.util.monitor.Expirable) PollingProber(org.mule.tck.probe.PollingProber) Assert.assertThat(org.junit.Assert.assertThat) JUnitLambdaProbe(org.mule.tck.probe.JUnitLambdaProbe) AbstractMuleContextTestCase(org.mule.tck.junit4.AbstractMuleContextTestCase) After(org.junit.After) Matchers.is(org.hamcrest.Matchers.is) ExpiryMonitor(org.mule.runtime.core.privileged.util.monitor.ExpiryMonitor) Before(org.junit.Before) JUnitLambdaProbe(org.mule.tck.probe.JUnitLambdaProbe) PollingProber(org.mule.tck.probe.PollingProber) Expirable(org.mule.runtime.core.privileged.util.monitor.Expirable) Test(org.junit.Test)

Aggregations

MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)55 List (java.util.List)34 Test (org.junit.Test)27 CountDownLatch (java.util.concurrent.CountDownLatch)22 ArrayList (java.util.ArrayList)20 Arrays (java.util.Arrays)14 Optional (java.util.Optional)14 Future (java.util.concurrent.Future)14 SECONDS (java.util.concurrent.TimeUnit.SECONDS)14 Before (org.junit.Before)13 Duration (io.airlift.units.Duration)11 Map (java.util.Map)10 ExecutorService (java.util.concurrent.ExecutorService)8 Context (android.content.Context)7 Math.toIntExact (java.lang.Math.toIntExact)7 Rule (org.junit.Rule)7 Threads.daemonThreadsNamed (com.facebook.airlift.concurrent.Threads.daemonThreadsNamed)6 Cache (com.google.common.cache.Cache)6 CacheBuilder (com.google.common.cache.CacheBuilder)6 IOException (java.io.IOException)6