Re: JavaMemoryModel: Can final fields change?

Date: Sat Oct 05 2002 - 14:04:06 EDT

The deal with final fields is actually pretty simple. In the original
Java Memory model, there were no guarantees made about final fields in
multithreaded situations. So you would need synchronization everywhere.
But this JMM is soon to disappear, and programmers can be (reasonably)
encouraged to program to a newer model.

Correct support for this does depend on the vintage of your JVM. Time to
dump those old 1.1 JVMs!

At any rate, here's the very basic version of the new model. All final
fields are (of course) set in the object's constructor. As long as no
threads other than the one performing construction see that object before
its constructor is finished, every thread will see the correctly set final

The semantics are actually a little more complicated than that (concerning
things like serialization), but there is nothing that should affect what
you are describing.

Your example is a little unclear. You say:

> A user creates a DataStorage instance in one thread, and before the
> constructor is finished, attempts to read something.

But you don't show how the user is doing this. If a reference to the
DataStorage or the Permission object escapes either constructor, stop it
from escaping. Then the user will be guaranteed to see the correctly
constructed value.

If you can't do this easily, you probably have some refactoring ahead of
you. The theory behind this is that the purpose of a constructor is to
construct an object, not to perform inter-thread communication. Sorry if
I am the bearer of bad news!

                                        Jeremy Manson

JavaMemoryModel mailing list -

This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:41 EDT