Using Spring and Apache Commons StopWatch to Monitor Java Code Execution Time
This article explains how to leverage Spring's org.springframework.util.StopWatch and Apache Commons Lang3 StopWatch for precise Java performance measurement, covering setup, usage examples, source code insights, important considerations, and practical code snippets for both libraries.
Background
When developing Java applications, measuring the execution time of tasks or code blocks is often done by printing the difference between start and end timestamps, which can become cumbersome and error‑prone, especially for complex or undocumented code sections.
This article introduces utility classes—Spring's org.springframework.util.StopWatch , Apache Commons Lang3 org.apache.commons.lang.time.StopWatch , and Guava's stopwatch—as convenient solutions for such scenarios.
Spring StopWatch Usage
The Spring StopWatch, located in the org.springframework.util package, provides millisecond‑level timing for synchronous single‑threaded code. To use it, include the Spring core dependency (already present in Spring MVC/Boot) and instantiate the class.
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
// Task 1
stopWatch.start("TaskOneName");
Thread.sleep(1000 * 3);
System.out.println("Current task: " + stopWatch.currentTaskName());
stopWatch.stop();
// Task 2
stopWatch.start("TaskTwoName");
Thread.sleep(1000 * 10);
System.out.println("Current task: " + stopWatch.currentTaskName());
stopWatch.stop();
// Task 3
stopWatch.start("TaskThreeName");
Thread.sleep(1000 * 10);
System.out.println("Current task: " + stopWatch.currentTaskName());
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
System.out.println(stopWatch.shortSummary());
System.out.println(stopWatch.currentTaskName()); // null after stop
System.out.println(stopWatch.getLastTaskName());
System.out.println(stopWatch.getLastTaskInfo());
System.out.println("Total time: " + sw.getTotalTimeMillis());
System.out.println("Task count: " + sw.getTaskCount());
System.out.println("All task details: " + sw.getTaskInfo());
}The StopWatch records each task's duration, provides detailed summaries, and can output total time, task count, and individual task information.
Spring StopWatch Source Highlights
public class StopWatch {
private final String id;
private boolean keepTaskList = true;
private final List
taskList;
private long startTimeMillis;
private boolean running;
private String currentTaskName;
private StopWatch.TaskInfo lastTaskInfo;
private int taskCount;
private long totalTimeMillis;
...
}Key fields include the unique ID, task list, start time, running flag, current task name, last task info, task count, and total elapsed time.
Important Notes for Spring StopWatch
Not thread‑safe; avoid synchronization.
Only one task can be active per instance.
A new task cannot be started before the previous one is stopped.
To time multiple concurrent tasks, create separate StopWatch instances.
Apache Commons StopWatch Usage
Apache's StopWatch (from org.apache.commons.lang3 ) offers similar functionality with additional features such as split, suspend, and resume.
public static void main(String[] args) throws InterruptedException {
StopWatch watch = StopWatch.createStarted();
Thread.sleep(1000);
System.out.println(watch.getTime());
System.out.println("Elapsed since start: " + watch.getTime() + "ms");
Thread.sleep(1000);
watch.split();
System.out.println("Time to first split: " + watch.getSplitTime());
Thread.sleep(1000);
watch.split();
System.out.println("Time to second split: " + watch.getSplitTime());
watch.reset();
watch.start();
Thread.sleep(1000);
System.out.println("After reset: " + watch.getTime());
watch.suspend();
System.out.println("Suspended for 2 seconds");
Thread.sleep(2000);
watch.resume();
System.out.println("After resume: " + watch.getTime());
Thread.sleep(1000);
watch.stop();
System.out.println("Final time: " + watch.getTime() + "ms");
System.out.println("Final time (seconds): " + watch.getTime(TimeUnit.SECONDS) + "s");
}The Apache StopWatch supports start‑stop, split points, reset, suspend, and resume, making it flexible for detailed performance analysis.
Conclusion
Using dedicated stopwatch utilities like Spring's and Apache Commons' StopWatch simplifies performance profiling, produces cleaner logs, and offers richer timing data compared to manual timestamp calculations, helping developers write more efficient and maintainable Java code.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.