Sunday, August 30, 2009

How to handle Constants in your application

Constants in Java
Even though Java does not have a constant type, you can achieve the same effect by declaring and initializing variables that are static, public, and final. After the variables have been initialized, their value cannot be changed. You can then access the constant value using the name of the variable joined to the name of its class with a period.

package blog.java;

public class ConstantClass {
public static final String westDirection = "West";
public static final String easttDirection = "East";
public static final String northDirection = "North";
public static final String southDirection = "South";
}

Alternatively, We can use the interface to declare the constants in Java. Any variables declared in Inferface are by default public, static and final.

package blog.java;

public interface Constants {
String westDirection = "West";
String easttDirection = "East";
String northDirection = "North";
String southDirection = "South";
}


Here is the sample to access the constants declared in the Interface and Class.

package blog.java;

public class UseConstants implements Constants {

public static void main(String[] args) {
//Retrive constants from the Interface.
System.out.println("Constants from the Interface: "+Constants.northDirection);
//Retrive constants from the Class.
System.out.println("Constants from the class: "+ConstantClass.southDirection);
}
}

Performance impact
While this seems to be the most common approach in a small sized application, this creates a memory hog in cases where there is a large number of constants but are sparingly used.
For example take a stock application, where the quotes of the stock are declared as constants. Say there are 10000 static variables of size x bytes. These are loaded as the class or interface is loaded by the JVM. The Static variable now occupies 10000x bytes of the space in memory. This memory is not collected by the Garbage collector of Java until the application comes down.
So if these constants are not required by the JVM during the entire life cycle of the application but only during the part of application, there is a potential degrade of the memory management in the application. In these cases, the application should have alternative approaches to handle the Constants in the application.