Showing posts with label static. Show all posts
Showing posts with label static. Show all posts

Sunday, 10 May 2009

The Essence of Static Initializers

SIB Explained

If you write a "static" Java class, by which I mean a class containing only static methods and static data, you may need a static initializer block (SIB) to initialize some of the private data (for example, java.util.HashMap that stores some mappings).

SIB is used to init static variables when the class is loaded. It resembles a method with no name, no arguments and no return type (not allowed to contain a return statement).

It is executed by VM when class is loaded. An alternative to SIBs is to write a private static method to perform initialization.

Problems in Static Initializers

An exception inside a static initializer will result in an ExceptionInInitializerError (which is a java.lang.LinkageError). One solution is to catch the exception inside the SIB and handle appropriately. This error may happen if initialise a data structure statically (after the SIB block). In this case, the data structure may not exist if accessed from within the SIB block.