2

I have a situation where I want to initialize some static, "constant" (ie. not modified after initialization) data structure. I'm doing this in the "static {}" code block. Is it guaranteed that this code block is never eceuted twice? Do I need synchronization in some special case?

Update: the answer is partly given in Are Java static initializers thread safe?

Remains the question: how can a static initializer be executed more than once? And does it matter? I guess it runs more than once for different static "instances", ie. in different webapp contexts and attached to different class loaders such that they don't "see" each other. Correct?

Community
  • 1
  • 1
user1050755
  • 11,218
  • 4
  • 45
  • 56
  • 1
    Each static initializer runs exactly once per class loader that initializes the class. Each of those initializations is operating on a different copy of the static fields. – Patricia Shanahan Mar 17 '13 at 17:11

2 Answers2

2

The JVM guarantees that all class static initializer blocks are called only once (when the class is first loaded). Since it will be called only once, there is no need for any synchronization code because that contradicts with Only Once rule.

Take a look here for more about class loading and static class initializer.

Quote from that page:

What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.   –David Flanagan

wchargin
  • 15,589
  • 12
  • 71
  • 110
Mr.Me
  • 9,192
  • 5
  • 39
  • 51
1

I want to initialize some static, "constant" (ie. not modified after initialization) data structure

Make that variable to final.

Like

public static final CONSTANT = 10;

OR

You can put that code in static block. Its execute once when class load.

Ajay S
  • 48,003
  • 27
  • 91
  • 111
  • Which variable? He is talking about a `static {}` block, isn't he? – NPE Mar 17 '13 at 17:08
  • Yes. It is more complicated. The right side throws an exception that must be caught. But that is not the question. Even in the case of a simple assignment there may be concurrency issues... – user1050755 Mar 17 '13 at 17:10