static init blocks
I'm working with an existing java class that is basically just a wrapper around a static map. The only public method is a static method that gives access to getting a value from the map.
The implementaiton seems to use something that I believe is unnecessary. I'd like to explain my view on this and see if anyone has any input.
The map, a static field, is initialized in a static init block. It is my understanding that this is guarranteed to occur before any use of an object of that class. I understand this to include any use of a static method.
The class that I am working with takes pains, in code, to make sure that the map is initialized before it is accessed by the static method. This seems wholely unnecessary according to my understanding. Does anyone see this differently?
Also, where is this kind of stuff documented? JVM Specification?
# 1
> The class that I am working with takes pains, in
> code, to make sure that the map is initialized before
> it is accessed by the static method. This seems
> wholely unnecessary according to my understanding.
> Does anyone see this differently?
Why does that seem unnecessary? Do you want to access the map while it is still uninitialized?
Look into the singleton pattern, it may give you a better way to accomplish this.
# 2
Well, if the map is static, and it is initialized in a static initializer, then there should be no way ever to access the map before it is initialized. Or is there something I am missing about static initializers?~Tim
# 4
> Why does that seem unnecessary?
Because it is.
> Do you want to access
> the map while it is still uninitialized?
It won't be accessed before the map is initialized since the JLS says that the static block will be executed before any static methods can be executed on the class.
Kaj
Ps. @Op. it's defined in the JLS
# 5
Yes, as far as I understand it, the static initializer executes when the class is loaded by the class loader, which is necessarily before any instance of the class is created, or any of it's methods can be called. Unless you have issues with access to the map, I'd say it's fine the way it is.