Common Utilities Classes and Methods In Google Guava

Google Guava library has multiple common utility methods that can be used in various applications. Below is a glimpse of the same.

com.google.common.base.Preconditions has various methods like checkArgument and checkState which are used to check the truth evaluation of the boolean parameter passed. It also has checkNotNull which evaluates whether the parameter passed is a non-null value and throws NullPointerException if it is null.

com.google.common.base.StandardSystemProperty has a list of common system environment properties defined.

com.google.common.base.Stopwatch can be used to measure the time difference between a set of operations. This can be consumed in simple ways by initiating it started and stopping the same once done and obtain the elapsed duration in a well formed readable format or converted into a desired unit for computational purposes. This simplifies the performance logging operation.

Stopwatch watch = Stopwatch.createStarted();
Thread.sleep(1000);
watch.stop();
System.out.println("Elapsed: " + watch); // prints 1.001 s
System.out.println("Elapsed: " + watch.elapsed(MILLISECONDS)); // prints 1000
System.out.println("Elapsed: " + watch.elapsed(MICROSECONDS)); // prints 1000500

Stopwatch can be enhanced by providing a com.google.common.base.Ticker which is a source which can be used to tweak the behavior of Stopwatch as below.

Ticker t = new Ticker() {
    @Override
    public long read() {
        return System.nanoTime() * 2;//Speed up by two fold
    }
};
Stopwatch watch = Stopwatch.createStarted(t);
Thread.sleep(1000);
watch.stop();
System.out.println("Elapsed: " + watch.elapsed(MILLISECONDS)); // prints 2000

com.google.common.base.Throwables has some nice utility methods to get the StackTrace as String. Also it implements getRootCause which can be used to obtain the root cause of an exception which has been nested in wrappers.