[concurrency-interest] Happens before relation between a static write and a read?

Roel Spilker R.Spilker at topdesk.com
Tue Feb 12 15:48:17 EST 2008

Hi Peter,

The initialization of a class, and with it its static members, are guaranteed to happen BEFORE any other code. The only catch is that if you create an instance during initialization, the order in which the fields are written to and read from is important. That even occurs if you create instances of another class that refers to your static members.

So the following code will create a NPE:

class Foo {
	static final Bar BAR = new Bar();
	static final Integer FOO_SIZE = Integer.valueOf(1);
	public static void main(String[] args) {

class Bar {
	int size = Foo.FOO_SIZE;

-----Oorspronkelijk bericht-----
Van: alarmnummer at gmail.com [mailto:concurrency-interest-bounces at cs.oswego.edu] Namens Peter Veentjer
Verzonden: dinsdag 12 februari 2008 18:51
Aan: concurrency-interest
Onderwerp: [concurrency-interest] Happens before relation between a static write and a read?

I have a question regarding a happens before relation.

Let me show you the example:

class Foo{

     private static Map somemap = new HashMap();

     public void bar(){

Is there a happens before relation of the write of somemap and the read in the bar method? My guess would be that there is no direct visible happens before relation, so in theory this example contains a data race. Is this assumption correct? I can imagine that in practice there is no problem because on a higher level some kind happens before relation is added (maybe the thread that loads the class, also starts the thread that executes the run methd, so  -> Thread.start happens before rule).
Concurrency-interest mailing list
Concurrency-interest at altair.cs.oswego.edu

More information about the Concurrency-interest mailing list