28 October 2011

Measuring Time to Minutest Precision With Guava

Other than profiling, have you ever encountered scenarios where you wanted to measure elapsed time from a predetermined past. A simple way of doing is to log the time (milliseconds or nanoseconds) into a long and then find the difference between two points. Here is a simple code.

public static void timer() throws Exception { 
long startMillis = System.currentTimeMillis(); 
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic 
long endMillis = System.currentTimeMillis(); 
System.out.println("Elapsed Time = " + (endMillis - startMillis));
// if i need to reset the start time, i need to do the following 
// startMillis = System.currentTimeMillis();
}  
}

If you are looking for only time difference between two points, you don't need to actually log the current time. It is enough if you start a clock (your own clock may be) at time t1 and stop it at time t2. If you want to measure time, you end up writing boiler plates. Guava has a little cute API for this.

Stopwatch is a simple API that mimics the functionality of a stopwatch. Here is the reincarnation of above code example.


public static void niceLittleAPI() throws Exception { 
Stopwatch stopWatch = new Stopwatch();  
stopWatch.start();  
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic  
System.out.println("Elapsed Time = " + stopWatch.elapsedMillis()); 
// if i need to reset the timer/clock, i need to do the following 
//stopWatch.reset(); 
// and my timer resets to zero
                                 // and if you want to stop the Stopwatch, just call
                                // stopWatch.stop();
}
What are the other advantages of using Stopwatch. I think it is an advantage of Stopwatch that it hides completely the mechanism it uses to keep time and in fact the user of the API is free to give his/her own Ticker.

Another nice addon is that you can get the elapsed time in days, hours, minutes, seconds, milliseconds, microseconds and nanoseconds which becomes very handy at times. A word of caution, Stopwatch is not thread safe and you have to figure it out how to make it thread-safe :-).

In order to understand the full power of Stopwatch, you may want to read Javadocs of Stopwatch, Timer and TimeUnit.

In my next post, we will see yet another Guava class and its use.

You may also want to check my previous post on Guava's Postconditions.

27 October 2011

Preconditions - (Java) Guava Collections Library

Fail early. It is applicable in life and programming.

The methods (or functions) are inevitable part of your code. The methods operate on the objects (or state of the system) and has a logic to do. Sometimes, the logic cannot (or rather must not be applied) due to non-availability of data (objects) or data being in an inconsistent state.

Let us take simple IPv4 address validator. Here is the code.

public static boolean isValidIPV4Address(String ipAddress)
{  
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

The above code is potentially dangerous if null is passed into the method. It crashes and brings everything to grinding halt. We can fix this by just adding a null check (and we have been often told to do that but we hardly follow it). The code will look something like this.


public static boolean isValidIPV4Address(String ipAddress)
{
                if(ipAddress == null)
                    throw new NullPointerException();
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

And thats how you fail early. You validate the inputs (irrespective of the number of arguments) and flag/fail early without changing the state if the arguments (inputs) sound weird. If you still operate on the data that is passed and change the state of the system, you add more pain by pushing the system to an inconsistent state. [Read Effective Java by Joshua Bloch if you haven't read it yet and if you want to be told by a Java expert]

If you think above is a good way, hold on. You have better way.

Guava (Google collection library) has a better way to handle this by using Preconditions. Replace the null check with one line statement and bingo Guava helps you to throw the exception.


public static boolean isValidIPV4Address(String ipAddress)
{  
Preconditions.checkNotNull(ipAddress); 
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

If "null" is passed, Preconditions.checkNotNull throws NullPointerException. You can also check for the validity of expression using Preconditions.checkArgument (check out Javadoc). Apart from improving the readability of code (to reduce boiler plates from code), it helps you to fail faster without causing any trouble to the state of the system.

Check out Preconditions. Here is the Javadoc of Preconditions. Don't you think that Preconditions is worth adding in our source code :-)

In the next post, we will see how to measure time with Guava's Stopwatch.


13 August 2011

Effort towards Perfection

Is it possible for a fresher or a newly formed company (any new entrant) to stand out and highly regarded among professionals (even among professionals with few years of experience)? I think, standing out in the crowd is no way related to how old are you. There isn't any age factor involved.

Standing out is the result of an attempt (even a failed attempt) towards perfection. In order to move towards perfection or excellence, you need a thought that perfection/excellence is a necessity (and not a value-add) and once you feel/absorb that the value is inherent in you. Perfection/excellence is not a stretch goal but an action, may be a base thing which you are supposed to do and a thing that you should naturally do.

I can't wait more to write this post after watching this video.


23 July 2011

First Program in Haskell

Recently, I stumbled upon a new programming paradigm - functional programming. Rather than focusing on variables, we define functions that does something. Without much of theory, let us quickly see an example

Write a program that finds triplets (a, b c) such that a, b and c are sides of a right angle triangle with none of the sides is greater than 20. I tried to write programs in Java and in Haskell as well. Here is the code snippet
Java
public class RightAngleTuples {
public static void main(String[] args) {
printTuples();
}
public static void printTuples() {
for(int c = 1; c <= 10; c++) {
for(int a = 1; a <= c; a++) {
for(int b = 1; b <= a; ++b ) {
if(a*a + b*b == c*c && a+b+c == 24) {
System.out.println(a + ", " + b + ", " + c);
}
}
}
}
}
}
Haskell
 Prelude> let triples = [(a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a], a^2 + b^2 == c^2, a+b+c == 24 ]
Prelude> triples
[(8,6,10)]
Initially it may appear that both the programs are different syntactically. But if you really see, while programming in an imperative languages, we need to think a lot of logic and variables (or memory location) that maintains the state of the program. It is programmers responsibility to keep the state sane. But in the case of functional programming, there is no concept of state. Everything is functions (obviously everything is logic).

If you are really interested to learn a new programming paradigm, i recommend Haskell. With my few hours of encounter with Haskell, i feel it changes one's thinking :-) and Learn you a Haskell for Great Good by Miran Lipovaca can be a great resource. (BTW, i copied the above example from the book and i promise that it is in fact last example that i will steal from the book). An heads-up: reading Haskell doesn't increase your value in job market :-), you cannot ask for 40% more hike but just improves your geeky quotient :-)

More stuffs on Haskell in coming weeks/months. Sharing never hurts :-) 

19 June 2011

After a while things go real hard

It appears to me that i stopped blogging forever. I literally can't think what to write. It is over a month i tried to post something here. The past two months have been so engaging and lot of events. I felt that i lost touch and became irrelevant. I needed so much courage to write this post because i honestly think that every post should add value to me and at least to my eyes i should feel that my thinking is slightly getting better. This self imposed exile of keeping away from my blog was not so easy. I m back and i think i should be consistent.

Here comes the real learning. The manager typically delegates work sacrificing hands-on. Though the delegation helps and often needed when one moves up, being hands-on is equally important. I m not here to say that you need to strike balance as i think that such balance never exist in reality. All i m saying is "dont lose touch". Why?

Hands-on experience helps in better abstraction. Abstraction is more meaningful only if one is consistently gets his/her hands dirt. Without hands-on, the abstraction deviates from its course and it turns out to be a poor abstraction. The poor abstraction gives us meaningless decisions and from there the things go real hard. From empowerment, people move towards irresponsibility and abandonment without their own knowledge simply because they are far from reality and most of their decisions/thinking will become outdated.

05 April 2011

Multiple Dimensions

What is 9460528400000000?

It is the distance traveled  by light in one year in meters. If the theory of big bang is true and if this universe started off from a tiny dot and still expanding till the moment we read this, what will be the size of universe. In which direction does it expand, may be in all possible direction. If you say the size of universe is infinite, how infinite is it? We tried to find the size of universe and we failed. And then we started to say "the size of observable universe"

Assume that we haven't invented numbers yet. How will you describe the size of universe? Having no number system is a dimension and having a number system is a dimension. You need both to depict or guess the size of universe. You need "no number system" dimension to say that the universe is massive and you need "number system" dimension to say or to give a feel of how massive is this universe. Each dimension has its own job of conveying something unique of the subject. And we can travel only certain level in each dimension. Assume that instead of sending light to measure distance, you decide to walk and count the number of kilometers. Beyond a point, even sending light and measuring the distance doesn't do well (as waiting time is more. If you send light, only your grandson can receive the light reflected from the subject) and you have to measure the light that is originated from the distant galaxy. There is clearly inherent limitation in each dimension and we have switch over to another dimension to visualize things (and to overcome the limitations of a dimension)

Unless the subject is caught in few dimensions, our understanding of the subject will be vague and limited. Multiple dimensions really help not only in finding the size of universe  (science) but also in solving general problems in life. :-)

04 April 2011

Design Patterns - How to Learn

Most often we encounter people whom they call themselves as expert in design patterns. They start off with the discussion saying that they know Singleton pattern - knowing little bit of what is singleton and completely ignorant of why Singleton is needed. While design pattern helped experts to improve their productivity and the quality of software they write, it hasn't done anything to novice designers like us. Right away, let me say that it is not the problem with the design patterns. It shows that the way we learn design patterns isn't right.

Learning design patterns starts with getting hands dirt with abstraction, hierarchy, encapsulation and loose coupling. All these attributes do not come easy and they evolve over a period of time with imagination. We have to visualize how a solution is better than the other and if we can solve by writing code, it really helps us to understand deeper.

Keeping that mind, i started to put together series of puzzles on software design to improve my design knowledge - particularly on object oriented software design for quite sometime. I would say that this method is changing the way i think. If you also want to get your hands dirt, you can find puzzles tagged as "Design for Fun".


Let me tell you, more puzzles are on the way.

27 March 2011

Software Design Puzzle #8 - Manufacturing Soaps

Assume that you are an expert in manufacturing many varieties of soaps - bath soaps, detergent soaps and all soaps in the earth. You have a magic recipes of soap making right from procuring raw materials till manufacturing soaps and shipping to stores. There are many processes involved in soap making and there are various flavors for each process. And some of the processes are optional and specific types of soaps. For example, you know that you to have add a lot of scents for bath/toilet soap and lot of whitening material for detergent soaps. 

The puzzle is to design the soap manufacturing with lot of processes/steps and all these processes/steps are sequential meaning that one process cannot start until the previous processes are complete. For instance, the process of shipping cannot happen until you make soap and you cannot make soaps until you form soap base and you cannot start soap base without raw materials.

Can you design soap manufacturing process where one step depends on so many previous steps. To induce your thinking, let us assume that you have the following processes/steps

  • Buy raw materials (can be different based on the soaps)
  • Mix raw materials
  • Form soap base
  • Make soaps
  • Package soaps
  • Ship It
You are free to add more steps but the key is to come up with a process that can be changed dynamically based on soap types that are going to be invented in future :-)

19 March 2011

Interesting Tools on Bytecode Manipulation

The last week, i got a chance to experiment on couple of bytecode manipulation APIs/tools and thought i can share my learning here.

Javassist is one of bytecode manipulation APIs that helps you to manipulate bytecode and it is simpler to use. I wrote a simple method profiler that takes class files as input and instruments the bytecodes in each method. Added, method start time, complete time and measured the time spent in the method. One good thing about Javassist is that you can directly add code written in Java that compiles on the fly while instrumentation. Seems like bytecode instrumentation is bit easier in Javassist. With Javassist, you can also do on the fly instrumentation during classloading phase.

Retroweaver is another bytecode manipulation tool that back ports the code compiled by Java 5 to Java 1.4. If you have written classes (or a third party classes/libraries) in Java 5 and if your production system still runs with Java 1.4/1.3/1.2, you may want to check out this tool. It is really cool to use latest APIs/libraries in old JVM. Retrotranslator is a similar tool.

Bytecode engineering seems to be very interesting.

07 March 2011

Why Contemporary Leadership?

In the ancient times, when locomotive motor was not invented, people who could afford, traveled using bullock carts and the people who weren't able to afford a pair of horses and cart traveled by legs. After the invention of motor and after having undergone industrial revolution, people travel by cars or public transportation. The means of transport has changed but the travel hasn't (moving from one point to another point).

Today, many of the organizations are finding ways for transportation of their organizations from point a (current state) to point b (the transformation state) and they are ready to do anything that ought to be done. They are not ready to travel using bullock carts. I think criticisms and cranky jokes of obsessed Gen Xs on Gen Y are fading away and by now people who will be getting old in near future have to anyway deal with Gen Ys by their sheer numbers. If they continue to criticize, i think it is not going to help the organization at large. Any organization needs contemporary ways of brining in more effectiveness.

These days, the people who join workplace (predominantly often called as Gen Ys) are value conscious and by their virtue of exposure, they tend to make decisions based on how things affect them. We can't question and debate on their way of thinking because this thinking is not unique to Gen Ys. It is part of human evolution. The evolution says, the size of human brain shrinks but its processing power increase every day and the way a 22 year old youth thought 20 years back and the way in which modern day youth thinks varies (greatly?).

While we talk about culture, workplace ethics, work ethics or professionalism, we got to understand that those are things that were once practiced and if we get too much carried away (or adamant) with yesteryears, it will be living in the past or reliving the past and who knows we may fail utterly when we relive. Our thoughts, approach and the way we achieve the vision has to be contemporary. This has to be freshness.

While leading, we ought to be contemporary and forward looking taking good things of the past which just gives enough direction and propulsion needed for the escape velocity and to puts us into the orbit. 

Freshness, productive, creativity and innovation applies even for leadership.

05 March 2011

Democratization of Organization

There are two ways of getting things done - in your own way, dictatorially and in the way others like. With the machines, you can be dictatorial meaning that you decide when the machine has to produce products. Switch on the power, boot up the machine, make sure that all parts work in unison and the product is produced. It is a continuous system where the output is predictable. But in the place where human beings are involved and the factor of motivation/passion more appropriate than fear, democratization or knowing what people have in their mind becomes absolute need. Human beings are discrete systems and they become quite unpredictable as mind and emotions are involved. 

There are two reasons why you democratize anything. First is due to the fact that you cannot make decisions or you don't feel responsible for something that is going to happen and the second reason is that you want to democratize to align your people towards the vision - may it be vision of a company or a country or the mankind. The first reason actually paves way to collective irresponsibility (like the climate change where everyone talks but no one does anything) and the second approach involves a lot hard work (likes of Mahatma Gandhi, Martin  Luther King). In order for effective democratization to become reality, first we have to accept that we can achieve it after a lot of failures. Initially, people tend to misunderstand the process of democratizing before understanding it completely which at the initial stage results to a lot of failure. After the initial failures and if you rally around your people during the failures, the democratization takes shape and becomes effective.

What are the signs of effective democratization? If you have at least few souls who give back far more than what they take back and if the ratio of number of souls that give back to the number of souls take back increases as the function of time, then you are staging yourself for better democratization.