[concurrency-interest] any read guarantees for static finals?

Yuval Shavit yshavit at akiban.com
Thu Feb 9 12:29:27 EST 2012


I've wondered this for a bit, and it finally came up in a stackoverflow
discussion recently. The JLS's description of final field read semantics
(as far as all threads seeing the state at least as it was at the end of
the constructor) only seems to apply to member fields -- not statics.
Specifically, JLS 17,5 refers only to object construction, not class
instantiation. JLS 13.4.9 states that primitives and Strings have to be
seen initialized, but makes no reference to other fields. So, are there
actually any guarantees for static finals?

For instance, is this class thread-safe, given that it uses a
non-thread-safe map which is initialized statically and then never modified?

    import java.util.*;
    public class PoorMansEnum {
        private static final Map<String,Integer> map = createMap();

        private static Map<String,Integer> createMap() {
            Map<String,Integer> map = new HashMap<String,Integer>();
            map.put("Foo", 1);
            map.put("Bar", 2);
            return map;
        }

        public static int valueOf(String value) {
            Integer integer = map.get(value);
            if (integer == null)
                throw new IllegalArgumentException("not a value: " + value);
            return integer;
        }
    }

Is there even a guarantee that every thread will see a non-null "map"? I
can't find anything in the JLS about it.

Thanks,
-Yuval
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120209/b160816a/attachment.html>


More information about the Concurrency-interest mailing list