List of usage examples for org.springframework.util StopWatch start
public void start() throws IllegalStateException
From source file:org.patientview.monitoring.ImportMonitor.java
public static void main(String[] args) { int importFileCheckCount = 0; while (true) { LOGGER.info("******** Import Logger & Monitor wakes up ********"); int monitoringFrequencyInMinutes = Integer.parseInt(getProperty("importerMonitor.frequency.minutes")); numberOfLinesToRead = monitoringFrequencyInMinutes / FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES; LOGGER.info("Import file counts will be logged every {} minutes, whereas a " + "health check will be done every {} minutes. Each monitoring will check the last {} lines " + "of the log", new Object[] { FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES, monitoringFrequencyInMinutes, numberOfLinesToRead }); StopWatch sw = new StopWatch(); sw.start(); importFileCheckCount = importFileCheckCount + FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES; /**//from w ww . j a v a 2 s.c om * Get the folders that will be monitored */ List<FolderToMonitor> foldersToMonitor = getFoldersToMonitor(); /** * Count the number of files in these folders */ setTheNumberOfCurrentFilesToFolderObjects(foldersToMonitor); /** * Log counts to a file */ logNumberOfFiles(foldersToMonitor); /** * If it is time, check the overall monitor stability as well */ if (importFileCheckCount == numberOfLinesToRead) { monitorImportProcess(foldersToMonitor); importFileCheckCount = 0; } else { LOGGER.info("Next monitoring will happen in {} minutes", numberOfLinesToRead - importFileCheckCount); } sw.stop(); LOGGER.info("ImportMonitor ends, it took {} (mm:ss)", new SimpleDateFormat("mm:ss").format(sw.getTotalTimeMillis())); /** * Sleep for (frequency - execution time) seconds */ long maxTimeToSleep = FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES * SECONDS_IN_MINUTE * MILLISECONDS; long executionTime = sw.getTotalTimeMillis(); long timeToSleep = maxTimeToSleep - executionTime; // if execution time is more than max time to sleep, then sleep for the max time if (timeToSleep < 0) { timeToSleep = maxTimeToSleep; } LOGGER.info("ImportMonitor will now sleep for {} (mm:ss)", new SimpleDateFormat("mm:ss").format(timeToSleep)); try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { LOGGER.error("Import Monitor could not sleep: ", e); // possible insomnia System.exit(0); } } }
From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java
@Test public void testDebatchByContainerPerformance() throws Exception { final List<Message> received = new ArrayList<Message>(); int count = 100000; final CountDownLatch latch = new CountDownLatch(count); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory); container.setQueueNames(ROUTE);/*from w w w . j a v a2s . com*/ container.setMessageListener((MessageListener) message -> { received.add(message); latch.countDown(); }); container.setReceiveTimeout(100); container.setPrefetchCount(1000); container.setTxSize(1000); container.afterPropertiesSet(); container.start(); try { BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(1000, Integer.MAX_VALUE, 30000); BatchingRabbitTemplate template = new BatchingRabbitTemplate(batchingStrategy, this.scheduler); // RabbitTemplate template = new RabbitTemplate(); template.setConnectionFactory(this.connectionFactory); MessageProperties props = new MessageProperties(); props.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); Message message = new Message(new byte[256], props); StopWatch watch = new StopWatch(); watch.start(); for (int i = 0; i < count; i++) { template.send("", ROUTE, message); } assertTrue(latch.await(60, TimeUnit.SECONDS)); watch.stop(); // System .out .println(watch.getTotalTimeMillis()); assertEquals(count, received.size()); } finally { container.stop(); } }
From source file:org.springframework.batch.core.scope.StepScopePerformanceTests.java
private int doTest(String name, String test) throws Exception { @SuppressWarnings("unchecked") ItemStreamReader<String> reader = (ItemStreamReader<String>) applicationContext.getBean(name); reader.open(new ExecutionContext()); StopWatch stopWatch = new StopWatch(test); stopWatch.start(); int count = 0; while (reader.read() != null) { // do nothing count++;//from w w w .j av a2s . c o m } stopWatch.stop(); reader.close(); logger.info(stopWatch.shortSummary()); return count; }
From source file:org.springframework.batch.item.xml.AbstractStaxEventWriterItemWriterTests.java
/** * Write list of domain objects and check the output file. *///w w w . j ava 2 s . c om @SuppressWarnings("resource") @Test public void testWrite() throws Exception { StopWatch stopWatch = new StopWatch(getClass().getSimpleName()); stopWatch.start(); for (int i = 0; i < MAX_WRITE; i++) { new TransactionTemplate(new ResourcelessTransactionManager()).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { try { writer.write(objects); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Exception encountered on write", e); } return null; } }); } writer.close(); stopWatch.stop(); logger.info("Timing for XML writer: " + stopWatch); XMLUnit.setIgnoreWhitespace(true); // String content = FileUtils.readFileToString(resource.getFile()); // System.err.println(content); XMLAssert.assertXMLEqual(new FileReader(expected.getFile()), new FileReader(resource.getFile())); }
From source file:org.springframework.boot.actuate.autoconfigure.MetricsFilter.java
private StopWatch createStopWatchIfNecessary(HttpServletRequest request) { StopWatch stopWatch = (StopWatch) request.getAttribute(ATTRIBUTE_STOP_WATCH); if (stopWatch == null) { stopWatch = new StopWatch(); stopWatch.start(); request.setAttribute(ATTRIBUTE_STOP_WATCH, stopWatch); }//from w w w .j a v a2 s . co m return stopWatch; }
From source file:org.springframework.boot.SpringApplication.java
/** * Run the Spring application, creating and refreshing a new * {@link ApplicationContext}./* w w w .ja v a 2s . com*/ * @param args the application arguments (usually passed from a Java main method) * @return a running {@link ApplicationContext} */ public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; configureHeadlessProperty(); SpringApplicationRunListeners listeners = getRunListeners(args); listeners.started(); try { context = doRun(listeners, args); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); } return context; } catch (Throwable ex) { try { listeners.finished(context, ex); this.log.error("Application startup failed", ex); } finally { if (context != null) { context.close(); } } ReflectionUtils.rethrowRuntimeException(ex); return context; } }
From source file:org.springframework.cloud.gateway.test.support.AbstractHttpServer.java
@Override public final void start() { synchronized (this.lifecycleMonitor) { if (!isRunning()) { String serverName = getClass().getSimpleName(); if (logger.isDebugEnabled()) { logger.debug("Starting " + serverName + "..."); }//from w w w. jav a2 s .c o m this.running = true; try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); startInternal(); long millis = stopWatch.getTotalTimeMillis(); if (logger.isDebugEnabled()) { logger.debug("Server started on port " + getPort() + "(" + millis + " millis)."); } } catch (Throwable ex) { throw new IllegalStateException(ex); } } } }
From source file:org.springframework.cloud.gateway.test.support.AbstractHttpServer.java
@Override public final void stop() { synchronized (this.lifecycleMonitor) { if (isRunning()) { String serverName = getClass().getSimpleName(); logger.debug("Stopping " + serverName + "..."); this.running = false; try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); stopInternal();//ww w. j a v a 2s . co m logger.debug("Server stopped (" + stopWatch.getTotalTimeMillis() + " millis)."); } catch (Throwable ex) { throw new IllegalStateException(ex); } finally { reset(); } } } }
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 ww w . ja v a2 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);/*from www.j av a2 s . c om*/ }); 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 }