Mastering Spring and Apache StopWatch: Precise Code Timing in Java
This article explains how to use Spring's org.springframework.util.StopWatch and Apache Commons' org.apache.commons.lang3.time.StopWatch to accurately measure execution time of sequential tasks in Java, covering setup, key methods, practical examples, and important usage considerations.
Background
When developing, you often need to record execution time of tasks or code blocks. The simplest way is to print the difference between start and end timestamps.
public static void main(String[] args) {
Long startTime = System.currentTimeMillis();
// your business code
Long endTime = System.currentTimeMillis();
Long elapsedTime = (endTime - startTime) / 1000;
System.out.println("Duration: " + elapsedTime + "s");
}While this works, writing such code repeatedly is cumbersome. A utility class that encapsulates timing logic is more convenient.
Spring StopWatch usage
The class org.springframework.util.StopWatch provides millisecond‑level timing for sequential single‑threaded tasks.
To use it, add the Spring core dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>Example:
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start("TaskOne");
Thread.sleep(3000);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
}The StopWatch records each task’s name, duration, total time, and can output a formatted summary.
Key methods
new StopWatch()– create a new stopwatch. void start(String taskName) – begin timing a named task. void stop() – stop the current task. String shortSummary() – brief total time description. String prettyPrint() – detailed task breakdown.
Apache Commons StopWatch usage
The class org.apache.commons.lang3.time.StopWatch offers similar functionality with additional features such as split, suspend, and resume.
Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>Example demonstrating start, split, reset, suspend, and resume:
public static void main(String[] args) throws InterruptedException {
StopWatch watch = StopWatch.createStarted();
Thread.sleep(1000);
watch.split();
System.out.println("Split time: " + watch.getSplitTime());
watch.suspend();
Thread.sleep(2000);
watch.resume();
watch.stop();
System.out.println("Total time: " + watch.getTime() + "ms");
}Important notes
StopWatch is not thread‑safe.
Only one task can be active at a time; start a new task after stopping the previous one.
For parallel timing, create separate StopWatch instances.
Conclusion
Using dedicated timing utilities like Spring’s or Apache’s StopWatch makes performance measurement cleaner and more expressive than manual timestamp calculations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
