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

Vitaly Davidovich vitalyd at gmail.com
Thu Feb 9 12:48:55 EST 2012


Static initialization guarantees visibility, so even without final on the
map it's guaranteed that all static initializing writes are seen across
cores (obviously subsequent writes to non-final non-volatile static fields
aren't guaranteed to be visible).

Sent from my phone
On Feb 9, 2012 12:32 PM, "Yuval Shavit" <yshavit at akiban.com> wrote:

> 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
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120209/dd49dec2/attachment.html>


More information about the Concurrency-interest mailing list