Example usage for org.springframework.util StopWatch start

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

Introduction

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

Prototype

public void start() throws IllegalStateException 

Source Link

Document

Start an unnamed task.

Usage

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;
        }//from www . jav a  2  s .  com

        @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  ww . j a  v a2 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 . j av a  2 s  . co 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();/*from w  w w  .  j av  a  2 s  .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.monitor.DirectChannelMetrics.java

private Object monitorSend(MethodInvocation invocation, MessageChannel channel, Message<?> message)
        throws Throwable {
    if (logger.isTraceEnabled()) {
        logger.trace("Recording send on channel(" + channel + ") : message(" + message + ")");
    }/* w  ww .  j  a v a  2s  .c  o  m*/
    final StopWatch timer = new StopWatch(channel + ".send:execution");
    try {
        timer.start();

        sendCount.incrementAndGet();
        sendRate.increment();

        Object result = invocation.proceed();

        timer.stop();
        if ((Boolean) result) {
            sendSuccessRatio.success();
            sendDuration.append(timer.getTotalTimeMillis());
        } else {
            sendSuccessRatio.failure();
            sendErrorCount.incrementAndGet();
            sendErrorRate.increment();
        }
        return result;
    } catch (Throwable e) {
        sendSuccessRatio.failure();
        sendErrorCount.incrementAndGet();
        sendErrorRate.increment();
        throw e;
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace(timer);
        }
    }
}

From source file:org.springframework.integration.monitor.DirectChannelMonitor.java

private Object monitorSend(MethodInvocation invocation, MessageChannel channel, Message<?> message)
        throws Throwable {

    if (logger.isTraceEnabled()) {
        logger.trace("Recording send on channel(" + channel + ") : message(" + message + ")");
    }//from   w ww.  j  av  a2 s. c o m

    final StopWatch timer = new StopWatch(channel + ".send:execution");

    try {
        timer.start();

        sendCount.incrementAndGet();
        sendRate.increment();

        Object result = invocation.proceed();

        timer.stop();
        if ((Boolean) result) {
            sendSuccessRatio.success();
            sendDuration.append(timer.getTotalTimeSeconds());
        } else {
            sendSuccessRatio.failure();
            sendErrorCount.incrementAndGet();
            sendErrorRate.increment();
        }
        return result;

    } catch (Throwable e) {
        sendSuccessRatio.failure();
        sendErrorCount.incrementAndGet();
        sendErrorRate.increment();
        throw e;
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace(timer);
        }
    }
}

From source file:org.springframework.integration.monitor.SimpleMessageHandlerMetrics.java

private void handleMessage(MethodInvocation invocation, Message<?> message) throws Throwable {
    if (logger.isTraceEnabled()) {
        logger.trace("messageHandler(" + this.handler + ") message(" + message + ") :");
    }/* w w w.  j  av a2 s.  com*/
    String name = this.name;
    if (name == null) {
        name = this.handler.toString();
    }
    StopWatch timer = new StopWatch(name + ".handle:execution");
    try {
        timer.start();
        this.handleCount.incrementAndGet();
        this.activeCount.incrementAndGet();

        invocation.proceed();

        timer.stop();
        this.duration.append(timer.getTotalTimeMillis());
    } catch (Throwable e) {
        this.errorCount.incrementAndGet();
        throw e;
    } finally {
        this.activeCount.decrementAndGet();
    }
}

From source file:org.springframework.integration.monitor.SimpleMessageHandlerMonitor.java

public void handleMessage(Message<?> message)
        throws MessageRejectedException, MessageHandlingException, MessageDeliveryException {
    if (logger.isTraceEnabled()) {
        logger.trace("messageHandler(" + handler + ") message(" + message + ") :");
    }/*from ww w  . j av  a2s  . c  om*/

    String name = this.name;
    if (name == null) {
        name = handler.toString();
    }
    StopWatch timer = new StopWatch(name + ".handle:execution");

    try {
        timer.start();
        handleCount.incrementAndGet();

        handler.handleMessage(message);

        timer.stop();
        duration.append(timer.getTotalTimeSeconds());
    } catch (RuntimeException e) {
        errorCount.incrementAndGet();
        throw e;
    } catch (Error e) {
        errorCount.incrementAndGet();
        throw e;
    }
}

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();
    for (int i = 0; i < count; i++) {
        rate.increment();/*www  . j av a 2  s  .  c om*/
    }
    watch.stop();
    double calculatedRate = count / (double) watch.getTotalTimeMillis() * 1000;
    assertEquals(calculatedRate, rate.getMean(), 4000000);
}

From source file:org.springframework.samples.portfolio.web.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];/* w ww .  jav  a2  s.  com*/
    }

    int port = 37232;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String homeUrl = "http://{host}:{port}/home";
    logger.debug("Sending warm-up HTTP request to " + homeUrl);
    HttpStatus status = new RestTemplate().getForEntity(homeUrl, Void.class, host, port).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<>();

    StandardWebSocketClient webSocketClient = new StandardWebSocketClient();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.afterPropertiesSet();

        String stompUrl = "ws://{host}:{port}/stomp";
        WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());
        stompClient.setTaskScheduler(taskScheduler);
        stompClient.setDefaultHeartbeat(new long[] { 0, 0 });

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompSessionHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompSessionHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(stompUrl, consumers.get(i), host, port);
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompSessionHandler producer = new ProducerStompSessionHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(stompUrl, producer, host, port);
        stompClient.setTaskScheduler(taskScheduler);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompSessionHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(60 * 1000, TimeUnit.MILLISECONDS)) {
            fail("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            fail("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}