Mastering Code Timing in Java: Spring and Apache StopWatch Deep Dive
This article explains why manual timestamp logging is cumbersome, introduces Spring's org.springframework.util.StopWatch and Apache Commons Lang's StopWatch, provides Maven dependencies, detailed usage examples, key methods, and important cautions for accurate performance measurement in Java applications.
Background
Measuring the execution time of code by manually printing start and end timestamps becomes cumbersome when many tasks need timing. Utility classes provide a cleaner approach.
Spring org.springframework.util.StopWatch
Dependency
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>Usage example
public static void main(String[] args) throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start("TaskOne");
Thread.sleep(3000);
System.out.println("Current task: " + sw.currentTaskName());
sw.stop();
sw.start("TaskTwo");
Thread.sleep(10000);
System.out.println("Current task: " + sw.currentTaskName());
sw.stop();
sw.start("TaskThree");
Thread.sleep(10000);
System.out.println("Current task: " + sw.currentTaskName());
sw.stop();
System.out.println(sw.prettyPrint());
System.out.println(sw.shortSummary());
System.out.println("Total time: " + sw.getTotalTimeMillis() + " ms");
}Key methods:
new StopWatch() – creates a stopwatch without starting a task.
start(String taskName) – begins timing a named task.
stop() – stops the current task.
currentTaskName() – returns the name of the running task.
prettyPrint() – detailed timing for all tasks.
shortSummary() – concise summary of total time.
getTotalTimeMillis() – total elapsed time in milliseconds.
Notes:
The class is not thread‑safe; use separate instances for concurrent timing.
Only one task can be active at a time; a new task must be started after the previous one is stopped.
Apache Commons Lang org.apache.commons.lang3.time.StopWatch
Dependency
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>Usage example
public static void main(String[] args) throws InterruptedException {
StopWatch watch = StopWatch.createStarted();
Thread.sleep(1000);
System.out.println("Elapsed: " + watch.getTime() + " ms");
watch.split();
System.out.println("Split time: " + watch.getSplitTime() + " ms");
watch.reset();
watch.start();
Thread.sleep(1000);
System.out.println("After reset: " + watch.getTime() + " ms");
watch.suspend();
Thread.sleep(2000);
watch.resume();
Thread.sleep(1000);
watch.stop();
System.out.println("Final elapsed: " + watch.getTime() + " ms");
System.out.println("Elapsed in seconds: " + watch.getTime(TimeUnit.SECONDS) + " s");
}Important methods:
createStarted() – creates and starts a stopwatch.
start() – starts timing (if not already started).
stop() – stops the current task.
split() – records a split point.
unsplit() – clears the split point.
reset() – clears all timing data.
suspend() / resume() – pause and continue timing.
getTime() – elapsed time since start or last reset.
getSplitTime() – time from start to the most recent split.
getTime(TimeUnit) – elapsed time in the specified unit.
Notes:
Not designed for concurrent use; each instance can time only one task at a time.
Supports split, suspend, and reset operations that Spring’s StopWatch does not provide.
Conclusion
Both org.springframework.util.StopWatch and org.apache.commons.lang3.time.StopWatch simplify performance measurement compared with manual timestamp calculations. Spring’s implementation is lightweight and suited for sequential single‑threaded tasks, while Apache Commons Lang adds split, suspend, and reset capabilities for more flexible timing scenarios.
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.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
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.
