Wednesday, January 29, 2014

Learning Guava -- Calibrating time using Stopwatch

Many of our day-to-day applications would need calibrating time taken between 2 points. In Java world we either depend on System.currentTimeMillis() or System.nanoTime(). But the pain here is, we have to do the required computations of getting to a proper granularity to understand the time taken.Would n't it be great it to have such an utility class which will give the required information in the granularity we need with minimum amount of boilerplate code?

Stopwatch is one such small and wonderful utility class in Guava which helps in calibrating elapsed time / duration between any 2 points in the logic. The advantage of using Guava's Stopwatch is you can get the elapsed time in any measure i.e. right from nanoseconds to days. This is possible because you can pass an enum argument type of TimeUnit class to get the elapsed time in the desired granularity.

Code snippet for the usage of the Stopwatch class:
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
/**
* Sample example demonstrating usage of Stopwatch API of Google Guava.
*
* @see <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Stopwatch.html">Guava Stopwatch</a>
*/
public final class StopwatchExample {
public final static void main(final String[] args) {
//Effective Guava v15.0, this is the one way of creating a Stopwatch instance.
final Stopwatch stopwatch = Stopwatch.createStarted();
//Sleep for few random milliseconds.
try {
Thread.sleep(new Random().nextInt(1000));
} catch (final InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
stopwatch.stop(); //optional
System.out.println("Elapsed time ==> " + stopwatch);
System.out.println("Elapsed time in Nanoseconds ==> " + stopwatch.elapsed(TimeUnit.NANOSECONDS));
System.out.println("Elapsed time in Microseconds ==> " + stopwatch.elapsed(TimeUnit.MICROSECONDS));
System.out.println("Elapsed time in Milliseconds ==> " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
//System.out.println("Elapsed time in Seconds ==> " + stopwatch.elapsed(TimeUnit.SECONDS));
//System.out.println("Elapsed time in Minutes ==> " + stopwatch.elapsed(TimeUnit.MINUTES));
}
}


Few caveats for using Stopwatch are you should not start an already started Stopwatch. One has to check if the Stopwatch is already running by invoking isRunning() method.
Stopwatch documentation says the following on the same:
Stopwatch methods are not idempotent; it is an error to start or stop a stopwatch that is already in the desired state.

Also, once I got burned down by StopWatch class of Apache Commons Lang. As I was working in an IDE on a Maven project, I could not relate to the difference between Stopwatch of Guava and StopWatch of Commons Lang as the class got auto imported into the code and then spent some 20 minutes trying to check my classpath, IDE setup, etc. Yes how stupid of me, right? So, please be careful in choosing the correct class.

Update on 05th April, 2015: After a fair bit of time here, I have moved on to GitHub hosted Octopress blogs. Please find me on http://P7h.org henceforth for all new updates.

Sunday, January 26, 2014

Learning Guava -- Load properties file using Guava

Guava code snippet for loading a properties file from classpath.
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import com.google.common.io.ByteSource;
import com.google.common.io.Resources;
/**
* Reads a properties file and print all the key value pairs to the console.
* Note: Writing to console is just for convenience here.
*/
public final class ReadPropertiesWithGuava {
public final static void main(final String[] args) {
final URL url = Resources.getResource("spring-config.properties");
final ByteSource byteSource = Resources.asByteSource(url);
final Properties properties = new Properties();
InputStream inputStream = null;
try {
inputStream = byteSource.openBufferedStream();
properties.load(inputStream);
properties.list(System.out);
} catch (final IOException ioException) {
ioException.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (final IOException ioException) {
ioException.printStackTrace();
}
}
}
}
}

For more info, please check Resources class of Guava.

Update on 05th April, 2015: After a fair bit of time here, I have moved on to GitHub hosted Octopress blogs. Please find me on http://P7h.org henceforth for all new updates.