Monday, October 27, 2008

Check memory usage by your java program

It is always helpul for us to know how much memory is our program consuming for its execution. It helps us to improve our program performance and optimize programs.
In Java, we have ways to do this programatically.
If you want to know programatically, you can use Runtime.totalMemory() to find out the total amount used by the JVM, and Runtime.freeMemory() to find out how much of that is still available (i.e. it's allocated to the JVM, but not allocated within the JVM - new objects can use this memory).
These are instance methods - use Runtime.getRuntime() to first get the singleton instance.

Sunday, October 19, 2008

Java best practices - Having multiple return statements.

Is having multiple return statement in a method a bad practice ?
We have seen or read in books saying we should have only one exit point for a method. But actually it depends on the case/scenario which we are dealing with. It is proposed to have a single exit point because it will be useful for logging or have some clean up code in one place.

It would be unwise deciding using multiple exit points in many cases, that we are better of returning from a method as soon as it is logically correct to do so.

for example :

public void DoStuff(Foo foo)
{ if (foo == null) return;
...
}

The above code is cleaner than
public void DoStuff(Foo foo)
{ if (foo != null)
{ ...
}
}

So, it is always fine to use multiple exit points where we need not do any logging/ clean up code and in places where it is absolutely logical to do so.