Monday, August 31, 2009

Loading Properties from a file in class path

A simple and smart way of loading a properties file which is located some where in the classpath

-------------------------

InputStream in = null;

Properties m_Properties = null;

in = ClassLoader.getSystemClassLoader().getResourceAsStream(fileName);

if (in != null)
{
m_Properties = new Properties ();

try {

m_Properties.load (in);

}

catch (IOException e)
{
e.printStackTrace();
}
}

Wednesday, July 8, 2009

Eliminating unnecessary log4j setup output

When using log4j for logging in your application, you may see a lot of log messages added by log4j when startup of the application which are not required. These will add to noise in your log files.

They will look something like

log4j: Retreiving an instance of org.apache.log4j.Logger.
log4j: Setting [Myclass] additivity to [false].
log4j: Level value for Myclass is [DEBUG].
log4j: Desired Level sub-class: [org.apache.log4j.Level]
log4j: Myclass level set to DEBUG
log4j: Class name: [org.apache.log4j.ConsoleAppender]
log4j: Setting property [target] to [System.out].
log4j: Parsing layout of class: "org.apache.log4j.PatternLayout"
log4j: Setting property [conversionPattern] to [%-5p %m%n].

These are the debug information from the logger itself. If you are using the XML config it looks like this:

log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true"
Turn the debug to false.

Difference between ++x and x++ in Java

++x is called pre-increment while x++ is called post-increment.

For Example:

-- Code --

int x = 5, y = 5;

System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6

System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6

----------


Check JDK Version used to compile a class

If you want to check the JDK version used to compile a class, use the below command

javap -verbose MyClass

Where MyClass is the class file you are checking.


Some example values it will return are

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50

Reading a String line by line

Given a string that isn't too long, What are the ways read it line by line?

Method 1:

BufferedReader reader = new BufferedReader(new StringReader());
reader.readLine();

Method 2:

final String eol = System.getProperty("line.separator");
output = output.substring(output.indexOf(eol + 1));

Method 3:

String[] lines = string.split(System.getProperty("line.separator"));


Method 4:

Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
}

Wednesday, May 20, 2009

Ways to implement singleton pattern in Java

There are many, time tested ways to implement Singleton pattern in Java all having its own advantage and drawbacks.

A simple and less confusing way to implement this is

public class
{
public final static Bar bar = new Bar();
private Bar()
{
// This prevents class instantiation from outside
}
public static Bar getBar()
{
return bar;
}
}

This is cleaner and readable code, but it does not give us an option of lazy initialization.
When you have a very large object or heavy construction code AND also have other accessible static methods or fields that might be used before an instance is needed, then and we need the lazy initialization option.

public class Bar
{
public final static Bar bar ;
private Bar()
{
// This prevents class instantiation from outside
}
public static Bar getBar()
{
synchronized(Bar.class)
{
if(bar == null)
{
bar = new Bar();
}
return bar;
}
}
}

The synchronized block helps to keep this instance creation thread safe.

If we are using Java 5 or above, we can use the additional feature provided by it for Double Checked locking. Without this, other threads are not guaranteed by the JMM ( Java Memory Model) to see the changes to its value.

You can refer this classic article on this subject:

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

public class Bar
{
public static volatile Bar bar ;

private Bar()
{
// This prevents class instantiation from outside
}

public static Bar getBar()
{
synchronized(Bar.class)
{
if(bar == null)
{
bar = new Bar();
}
return bar;
}
}
}


Note the volatile keyword which does the trick.

Adding
protected Object clone()
{
throw new CloneNotSupportedException();
}

Would make Singletons better !!.

we have to choose the design based on requirement and make use of Singletons very carefully in our applications.

Cheers
Vinay

Thursday, April 16, 2009

What to know as a Java Developer?

For a Software profession, every day there are new things to learn. With constant updating of technologies surrounding our technical and domain expertise, we should have a strong base knowledge around with we have to build our technical skills in line with new developments.

For a java developer, we should build our base knowledge around fundamentals of Java language and be strong in java interfaces, generics, annotations, concurrency etc., It's easy to learn quickly new technologies when you master the fundamentals.

Here is a list of things which (out of many things) a java developer must be aware of.

1. How does JVM work?
2. Improvements on language from major version changes (Generics, Annotations, Enums ...).
3. What are the OOPS concepts and how do they Implemented in Java?
4. Understand design pattern
5. Coding Conventions.
6. Build tool (Ant) or Project Management Tool (Maven).
7. At least basic knowledge of some popular frameworks such as Struts, springs, hibernate.
8. Writing test cases using Junit.
9. Good knowledge of Eclipse ( or any popular IDE ).
10. Knowledge of using log4j.

Saturday, April 4, 2009

why not ALWAYS use ArrayLists in Java?

If you need a collection of primitives, then an array may well be the best tool for the job. Boxing is a comparatively expensive operation. For a collection (not including maps) of primitives that will be used as primitives, I almost always use an array to avoid repeated boxing and unboxing.

I rarely worry about the performance difference between an array and an ArrayList, however. If a List will provide better, cleaner, more maintainable code, then I will always use a List (or Collection or Set, etc, as appropriate, but your question was about ArrayList) unless there is some compelling reason not to. Performance is rarely that compelling reason.

Using Collections almost always results in better code, in part because arrays don't play nice with generics, as Johannes Weiß already pointed out in a comment, but also because of so many other reasons:

  • Collections have a very rich API and a large variety of implementations that can (in most cases) be trivially swapped in and out for each other
  • A Collection can be trivially converted to an array, if occasional use of an array version is useful
  • Many Collections grow more gracefully than an array grows, which can be a performance concern
  • Collections work very well with generics, arrays fairly badly
  • As TofuBeer pointed out, array covariance is strange and can act in unexected ways that no object will act in. Collections handle covariance in expected ways.
  • arrays need to be manually sized to their task, and if an array is not full you need to keep track of that yourself. If an array needs to be resized, you have to do that yourself.

All of this together, I rarely use arrays and only a little more often use an ArrayList. However, I do use Lists very often (or just Collection or Set). My most frequent use of arrays is when the item being stored is a primitive and will be inserted and accessed and used as a primitive. If boxing and unboxing every become so fast that it becomes a trivial consideration, I may revisit this decision, but it is more convenient to work with something, to store it, in the form in which it is always referenced. (That is, 'int' instead of 'Integer'.)

Array or List in Java. Which is faster ?

The Java way is that you should consider what data abstraction most suits your needs. Remember that in Java a List is an abstract, not a concrete data type. You should declare the strings as a List, and then initialize it using the ArrayList implementation.

List<String> strings = new ArrayList<String>();

This separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming.

An ArrayList implements the List Abstract Data Type using an array as its underlying implementation. Access speed is virtually identical to an array, with the additional advantages of being able to add and subtract elements to a List (although this is an O(n) operation with an ArrayList) and that if you decide to change the underlying implementation later on you can. For example, if you realize you need synchronized access, you can change the implementation to a Vector without rewriting all your code.

In fact, the ArrayList was specifically designed to replace the low-level array construct in most contexts. If Java was being designed today, it's entirely possible that arrays would have been left out altogether in favor of the ArrayList construct.

Since arrays keep all the data in a contiguous chunk of memory (unlike Lists), would the use of an array to store thousands of strings cause problems ?

In Java, all collections store only references to objects, not the objects themselves. Both arrays and ArrayList will store a few thousand references in a contiguous array, so they are essentially identical. You can consider that a contiguous block of a few thousand 32-bit references will always be readily available on modern hardware. This does not guarantee that you will not run out of memory altogether, of course, just that the contiguous block of memory requirement is not difficult to fufil.

Wednesday, February 18, 2009

Java - Frequently used Java Libraries

List of most commonly used Java Libraries

  • JUnit for unit testing
  • Tomcat or Jetty as servlet container
  • Spring for configuration and glueing code together
  • Hibernate for object persistence
  • C3P0 for database connection pooling
  • Lucene for fulltext search
  • Log4J for logging
  • Apache Commons for a whole bunch of stuff: language utilities (see StringUtils), special collections, IO, file uploads, validation, etc.
  • POI for reading/writing MS Office file formats
  • PDFBox for manipulating PDFs
  • Velocity for templating
  • Bouncy Castle for Security/Cryptography
  • JOrtho The Java Spell Checker

Wednesday, January 14, 2009

How to get the name of the currently executing method in Java ?

We can get the name of currently executing method using
Thread.currentThread.getStackTrace().
This will usually contain the method we are calling. But there are some pitfalls.
Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

You can use the below code

final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
ste[0].getMethodName(); // Will return the stack trace's first method name