Páginas

Friday, July 23, 2010

Java static blocks

During the course of the year I found out about a very interesting thing in Java, the static blocks. Java has a special word for variables that are initialized once per class, instead of once per instance of the class. That word is static.

static int class_variable = 0;

This way, all the instances of the class share this variable (this also means you have to be careful about concurrency control). Now, what if you want to do this with a Collection, instead of a primitive type?

That's where static blocks come in handy. Imagine we have this:

static HashMap<Integer,String> sharedHash = new HashMap<Integer,String>();

What we want now is to populate the HashMap, either from hardcoded values or a function that does the job. The solution is simple, a static block!

static
{
    sharedHash.put(1,"one");
    this.populateHash(sharedHash);
}

This populates the HashMap only once, and only when the first instance of the class is created, saving a lot of unnecessary processing and memory usage.

No comments: