views:

330

answers:

4

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?

+1  A: 

I 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.

mamboking
well... how does a newly-spawned thread know that the class has already been loaded? it still has to talk to something central to find that out.
kolosy
That's the responsibilities of the virtual machine. If the virtual machine don't have any clever tricks/does locking in order to realize this, I wouldn't want to develop a single .NET application ever.
nos
The virtual machine keeps a list of classes it's already loaded. When a class needs to be acted upon, the vm looks at the list to see if it's loaded. If it is, static initializers never even come into play. If not, the class loader takes over and it calls the initializer.
mamboking
A: 

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.

nos
I am more on the 'hope' side. As Ronald Reigan used to say 'doverjaj no proverjaj' or, in English trust but verify. Can you think of any way to verify that static initializers should not be a concern?
mfeingold
A: 

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.

Nick Robinson
A: 

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.

Scott Dorman