Friday, April 26, 2013

Java: Initializing Class and objects of Class - Order of execution of different code blocks

A Java class contains instance variables, static class level variables, static initialization block, instance initialization block, constructor, static methods, instance methods.

Order of execution:
1. Class level attributes (static variables) are initialized to value which is specified (explicit value) or to default value if no explicit value given and static initialization block are called as per their order (top to down) in java class. If we try to access field before it is declared in class initialization block, it gives Illegal forward reference compile time error.

2. Instance fields are initialized to explicit or default value and instance initialization block is called as per their sequence.


Below example class gives more details:



public class TestInit {

//instance variable
String b = "VAL1";

//instance level initialization block
{
System.out.println("instance initialization block I called");
System.out.println("instance level variable 'b' is already initialized to:"+ b );
}

//class level initialization block
static{
System.out.println("static initialization block I called");
}

//Class level field
static int a = 5;

//class level initialization block
static{
System.out.println("static initialization block II called");
System.out.println("class level variable 'a' is already initialized to:"+ a);
}

//instance variable
int c = 10;

//instance level initialization block
{
System.out.println("instance initialization block II called");
System.out.println("instance level variable 'c' is already initialized to:"+ c);
}



/**
* @param args
*/
public static void main(String[] args) {
TestInit t = new TestInit();

}

}

Output after running above class:


static initialization block I called
static initialization block II called
class level variable 'a' is already initialized to:5
instance initialization block I called
instance level variable 'b' is already initialized to:VAL1
instance initialization block II called
instance level variable 'c' is already initialized to:10




Saturday, April 20, 2013

Threadlocal cache in web application

Application server maintains thread pool which is used to allocate thread to process client requests.
When you want to or plan to use thread local cache in web application, take care of clearing cache before request processing is complete. Because if by mistake your thread local cache data is not cleared from cache, when that thread processes next request, cached data is still there. If actual data is changed in between the two request, you will still get old data from cache. It becomes very difficult to find out root cause of problems which occurs due to wrong implementation of threadlocal cache in web applications. So always take care whenever you decide to use threadlocal cache in web applications to improve performance. Your comments are most welcome.