Static initializers are supposed to be executed once before the first reference to the class. It means that every time a class is accessed, a check should be performed whether the static initializers for the class are executed.
It seems that in multithreaded environment classes with non-trivial static initializers can be a source of contention because of synchronization necessary when the class is accessed by multiple threads.
My question is what is the best way to minimize the impact of such implicit locks on the class definitions introduced by static initializers?
views:
330answers:
4I don't think there's much contention. The initializers are run when the class is loaded. If the class is already loaded then no checks have to occur.
The specs says "executed at an implementation-dependent time prior to the first use of a static field of that class.".
So, one can assume(or hope if you're pessimistic) that the implementation have figured out that they need to care about thread synchronization.
I believe this works as part of JIT compilation. Once the static initializer has been jitted and run, it no longer needs to run it and thus no synchronization problems with multiple threads. And of course the JIT engine will be thread-safe.
Nick.
The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
- An instance of the class is created.
- Any of the static members of the class are referenced
It should be the responsibility of the class loader to handle concurrency issues when calling static constructors.