Calculate Timings using Commons Lang StopWatch

You need to calculate timings of your code execution so you know how long a particular method or some block in your code take to finish it execution. Basically you can do this by capturing the start time and the end time using System.currentTimeMillis() and find the different. Another way to do it is to use the StopWatch class from Apache Commons Lang library. The StopWatch class can be found in the org.apache.commons.lang.time package.

The simplest steps to use the StopWatch is to create an instance of the StopWatch class, start the stopwatch by calling the start() method. After the stopwatch is started you can execute the target method or block of code you want to watch and call the stop() method to complete the timing session. To get the time of the stopwatch you can call the getTime() method.

Now, let’s see the code for the process described above.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingOne();
    }

    private void timingOne() {
        // Create an instance of StopWatch.
        StopWatch stopWatch = new StopWatch();

        // Start the watch, do some task and stop the watch.
        stopWatch.start();
        doSomeTask(5000);
        stopWatch.stop();

        // Print out the total time of the watch
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Here is the output of the code above:

Time: 5000

Beside doing a simple timing calculation using the start() and stop() followed by the getTime() methods, the StopWatch class also provides methods for splitting the time, suspend and resuming the stopwatch. You can use the split(), suspend() and resume() method respectively. To get the split time you can call the toSplitString() method.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingTwo();
    }    

    private void timingTwo() {
        // Create an instance of StopWatch and start the stopwatch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Do some task and split the stopwatch time.
        doSomeTask(3000);
        stopWatch.split();
        System.out.println("Split 1: " + stopWatch.toSplitString());

        // Suspend the stopwatch and resume the stopwatch.
        stopWatch.suspend();
        doSomeTask(4000);
        stopWatch.resume();

        // Do some task and split the stopwatch time.
        doSomeTask(2500);
        stopWatch.split();
        System.out.println("Split 2: " + stopWatch.toSplitString());

        // Do some task and split the stopwatch time.
        doSomeTask(1000);
        stopWatch.split();
        System.out.println("Split 3: " + stopWatch.toSplitString());

        // Stop the stopwatch and the the total execution time.
        stopWatch.stop();
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will output something like this:

Split 1: 0:00:03.000
Split 2: 0:00:05.525
Split 3: 0:00:06.525
Time: 6525

Another method that you can find in the StopWatch class is the getStartTime() which will return the stopwatch start time. The reset() method will reset the stopwatch. To remove a split you can call the unsplit() method.

How to implement the hashCode and equals method using Apache Commons?

This code snippet show you how to use HashCodeBuilder and EqualsBuilder class from the Apache  Commons Lang library to implement the hashCode() and equals() method of an object. To use both of these classes we just need to create instance of these class and append the properties that we will use the calculate the hashcode and to test for equality.

Implementing the hashCode() method first by creating the hashCode() method. Add the @Override annotation to make sure that we’ve override the correct method. Then we create an instance of HashCodeBuilder. Append the fields we’re gonna use to calculate the hashcode. The final result of the actual hashcode can be obtained by calling the toHashCode() from the instance of HashCodeBuilder.

/**
 * Implement the hashCode method using HashCodeBuilder.
 */
@Override
public int hashCode() {
    return new HashCodeBuilder().append(id).append(name).toHashCode();
}

We do the same to create the equals() method. First create the method, it takes a single argument type of java.lang.Object. Add the @Override annotation to make sure we override the correct method. On the first line you can check to see if the passed object is an instance of the same object, we use the instanceof operator. We then compare the values stored in both object using the EqualsBuilder class. To get the equality result you must remember to call the isEquals() method.

/**
 * Implement the equals method using the EqualsBuilder.
 */
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof DummyUser)) {
        return false;
    }
    DummyUser that = (DummyUser) obj;
    return new EqualsBuilder().append(this.id, that.id)
            .append(this.name, that.name).isEquals();
}

Here the complete look of the snippet.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class DummyUser {
    private Long id;
    private String name;

    /**
     * Constructor to create an instance of this class.
     */
    public DummyUser() {
    }

    public static void main(String[] args) {
        DummyUser user1 = new DummyUser();
        user1.setId(10L);
        user1.setName("Carol");

        DummyUser user2 = new DummyUser();
        user2.setId(10L);
        user2.setName("Carol");

        System.out.println("user1.hashCode() = " + user1.hashCode());
        System.out.println("user2.hashCode() = " + user2.hashCode());

        System.out.println("user1.equals(user2) = " + user1.equals(user2));
    }

    //
    // Getters & Setters
    //
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Implement the hashCode method using HashCodeBuilder.
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(id).append(name).toHashCode();
    }

    /**
     * Implement the equals method using the EqualsBuilder.
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DummyUser)) {
            return false;
        }
        DummyUser that = (DummyUser) obj;
        return new EqualsBuilder().append(this.id, that.id)
                .append(this.name, that.name).isEquals();
    }
}

The result of our code are:

user1.hashCode() = 64902380
user2.hashCode() = 64902380
user1.equals(user2) = true