Example usage for org.springframework.util StopWatch StopWatch

List of usage examples for org.springframework.util StopWatch StopWatch

Introduction

In this page you can find the example usage for org.springframework.util StopWatch StopWatch.

Prototype

public StopWatch() 

Source Link

Document

Construct a new StopWatch .

Usage

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testAggPerf() throws InterruptedException, ExecutionException, TimeoutException {
    AggregatingMessageHandler handler = new AggregatingMessageHandler(
            new DefaultAggregatingMessageGroupProcessor());
    handler.setCorrelationStrategy(message -> "foo");
    handler.setReleaseStrategy(new MessageCountReleaseStrategy(60000));
    handler.setExpireGroupsUponCompletion(true);
    handler.setSendPartialResultOnExpiry(true);
    DirectChannel outputChannel = new DirectChannel();
    handler.setOutputChannel(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);//from w ww . j a va 2 s  .  c  o  m
    });

    SimpleMessageStore store = new SimpleMessageStore();

    SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory(
            SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE);

    store.setMessageGroupFactory(messageGroupFactory);

    handler.setMessageStore(store);

    Message<?> message = new GenericMessage<String>("foo");
    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(message);
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(60000, result.size());
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testAggPerfDefaultPartial() throws InterruptedException, ExecutionException, TimeoutException {
    AggregatingMessageHandler handler = new AggregatingMessageHandler(
            new DefaultAggregatingMessageGroupProcessor());
    handler.setCorrelationStrategy(message -> "foo");
    handler.setReleasePartialSequences(true);
    DirectChannel outputChannel = new DirectChannel();
    handler.setOutputChannel(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);/*  w w w  .j av  a  2  s.c  o m*/
    });

    SimpleMessageStore store = new SimpleMessageStore();

    SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory(
            SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE);

    store.setMessageGroupFactory(messageGroupFactory);

    handler.setMessageStore(store);

    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(
                MessageBuilder.withPayload("foo").setSequenceSize(120000).setSequenceNumber(i + 1).build());
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(120000, result.size());
    assertThat(stopwatch.getTotalTimeSeconds(), lessThan(60.0)); // actually < 2.0, was many minutes
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testCustomAggPerf() throws InterruptedException, ExecutionException, TimeoutException {
    class CustomHandler extends AbstractMessageHandler {

        // custom aggregator, only handles a single correlation

        private final ReentrantLock lock = new ReentrantLock();

        private final Collection<Message<?>> messages = new ArrayList<Message<?>>(60000);

        private final MessageChannel outputChannel;

        private CustomHandler(MessageChannel outputChannel) {
            this.outputChannel = outputChannel;
        }/*  w  w w  .jav  a  2  s  .c o m*/

        @Override
        public void handleMessageInternal(Message<?> requestMessage) {
            lock.lock();
            try {
                this.messages.add(requestMessage);
                if (this.messages.size() == 60000) {
                    List<Object> payloads = new ArrayList<Object>(this.messages.size());
                    for (Message<?> message : this.messages) {
                        payloads.add(message.getPayload());
                    }
                    this.messages.clear();
                    outputChannel.send(getMessageBuilderFactory().withPayload(payloads)
                            .copyHeaders(requestMessage.getHeaders()).build());
                }
            } finally {
                lock.unlock();
            }
        }

    }

    DirectChannel outputChannel = new DirectChannel();
    CustomHandler handler = new CustomHandler(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);
    });
    Message<?> message = new GenericMessage<String>("foo");
    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(message);
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(60000, result.size());
}

From source file:org.springframework.integration.core.MessageIdGenerationTests.java

@Test
@Ignore/*from   w w  w.j  a va  2  s . co  m*/
public void performanceTest() {
    int times = 1000000;
    StopWatch watch = new StopWatch();
    watch.start();
    for (int i = 0; i < times; i++) {
        new GenericMessage<Integer>(0);
    }
    watch.stop();
    double defaultGeneratorElapsedTime = watch.getTotalTimeSeconds();

    Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator");
    ReflectionUtils.makeAccessible(idGeneratorField);
    ReflectionUtils.setField(idGeneratorField, null, (IdGenerator) () -> TimeBasedUUIDGenerator.generateId());
    watch = new StopWatch();
    watch.start();
    for (int i = 0; i < times; i++) {
        new GenericMessage<Integer>(0);
    }
    watch.stop();
    double timebasedGeneratorElapsedTime = watch.getTotalTimeSeconds();

    logger.info("Generated " + times + " messages using default UUID generator " + "in "
            + defaultGeneratorElapsedTime + " seconds");
    logger.info("Generated " + times + " messages using Timebased UUID generator " + "in "
            + timebasedGeneratorElapsedTime + " seconds");

    logger.info("Time-based ID generator is " + defaultGeneratorElapsedTime / timebasedGeneratorElapsedTime
            + " times faster");
}

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
@Ignore//  w ww .ja va 2 s  .  c  o  m
public void testMessageHistoryWithHistoryPerformance() {
    ConfigurableApplicationContext acWithHistory = new ClassPathXmlApplicationContext(
            "perfWithMessageHistory.xml", MessageHistoryIntegrationTests.class);
    ConfigurableApplicationContext acWithoutHistory = new ClassPathXmlApplicationContext(
            "perfWithoutMessageHistory.xml", MessageHistoryIntegrationTests.class);

    SampleGateway gatewayHistory = acWithHistory.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannelHistory = acWithHistory.getBean("endOfThePipeChannel",
            DirectChannel.class);
    endOfThePipeChannelHistory.subscribe(message -> {
        MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
        replyChannel.send(message);
    });

    SampleGateway gateway = acWithoutHistory.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = acWithoutHistory.getBean("endOfThePipeChannel", DirectChannel.class);
    endOfThePipeChannel.subscribe(message -> {
        MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
        replyChannel.send(message);
    });

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    for (int i = 0; i < 10000; i++) {
        gatewayHistory.echo("hello");
    }
    stopWatch.stop();
    logger.info("Elapsed time with history 10000 calls: " + stopWatch.getTotalTimeSeconds());
    stopWatch = new StopWatch();
    stopWatch.start();
    for (int i = 0; i < 10000; i++) {
        gateway.echo("hello");
    }
    stopWatch.stop();
    logger.info("Elapsed time without history 10000 calls: " + stopWatch.getTotalTimeSeconds());
    acWithHistory.close();
    acWithoutHistory.close();
}

From source file:org.springframework.integration.jdbc.lock.JdbcLockRegistryDifferentClientTests.java

@Test
public void testExclusiveAccess() throws Exception {
    DefaultLockRepository client1 = new DefaultLockRepository(dataSource);
    client1.afterPropertiesSet();// www.  j av  a2s  . c o m
    final DefaultLockRepository client2 = new DefaultLockRepository(dataSource);
    client2.afterPropertiesSet();
    Lock lock1 = new JdbcLockRegistry(client1).obtain("foo");
    final BlockingQueue<Integer> data = new LinkedBlockingQueue<Integer>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    lock1.lockInterruptibly();
    Executors.newSingleThreadExecutor().execute(() -> {
        Lock lock2 = new JdbcLockRegistry(client2).obtain("foo");
        try {
            latch1.countDown();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            lock2.lockInterruptibly();
            stopWatch.stop();
            data.add(4);
            Thread.sleep(10);
            data.add(5);
            Thread.sleep(10);
            data.add(6);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock2.unlock();
        }
    });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    data.add(1);
    Thread.sleep(1000);
    data.add(2);
    Thread.sleep(1000);
    data.add(3);
    lock1.unlock();
    for (int i = 0; i < 6; i++) {
        Integer integer = data.poll(10, TimeUnit.SECONDS);
        assertNotNull(integer);
        assertEquals(i + 1, integer.intValue());
    }
}

From source file:org.springframework.integration.support.management.ExponentialMovingAverageRateTests.java

@Test
@Ignore // tolerance needed is too dependent on hardware
public void testRate() {
    ExponentialMovingAverageRate rate = new ExponentialMovingAverageRate(1, 60, 10);
    int count = 1000000;
    StopWatch watch = new StopWatch();
    watch.start();/* www  .ja v a 2s  .c om*/
    for (int i = 0; i < count; i++) {
        rate.increment();
    }
    watch.stop();
    double calculatedRate = count / (double) watch.getTotalTimeMillis() * 1000;
    assertEquals(calculatedRate, rate.getMean(), 4000000);
}

From source file:org.springframework.load.AbstractTest.java

/**
 * Construct a new AbstractTest. The object must be further configured
 * by its JavaBean properties and/or by inheritance of properties
 * from the TestSuite it runs it. The setTestSuite() method must
 * be invoked by the managing AbstractTestSuite.
 *///from w  ww. java2s  .c o  m
protected AbstractTest() {
    testFailedExceptions = new LinkedList();
    runningTimer = new StopWatch();
    runningTimer.setKeepTaskList(false);

    pauseTimer = new StopWatch();
    pauseTimer.setKeepTaskList(false);

    elapsedTimer = new StopWatch();
    elapsedTimer.setKeepTaskList(false);
}

From source file:org.springframework.statemachine.recipes.support.RunnableAction.java

@Override
public final void execute(StateContext<String, String> context) {
    if (!shouldExecute(id, context)) {
        return;/*from www  .ja  v  a2s .c  o m*/
    }
    StopWatch watch = new StopWatch();
    String logId = (id == null ? "" : (" id=" + id));
    log.info("Executing runnable" + logId);
    if (log.isDebugEnabled()) {
        watch.start();
    }
    try {
        onPreExecute(id, context);
        runnable.run();
        onSuccess(id, context);
    } catch (Exception e) {
        onError(id, context, e);
    } finally {
        onPostExecute(id, context);
    }
    if (log.isDebugEnabled()) {
        watch.stop();
        log.debug("Runnable execution took " + watch.getTotalTimeMillis() + " ms" + logId);
    }
}

From source file:org.springframework.ws.soap.PerformanceTest.java

public static void main(String[] args) throws Exception {
    StopWatch stopWatch = new StopWatch();

    try {/*w  ww. jav  a2  s .  c om*/
        saaj(stopWatch);
        axiom(stopWatch, false, false);
        axiom(stopWatch, true, false);
        axiom(stopWatch, false, true);
        axiom(stopWatch, true, true);
        stroap(stopWatch, false, false);
        stroap(stopWatch, true, false);
        stroap(stopWatch, false, true);
        stroap(stopWatch, true, true);

    } finally {
        System.out.println(stopWatch.prettyPrint());
    }
}