Are final static variables thread safe in Java?

前端 未结 8 883
盖世英雄少女心
盖世英雄少女心 2020-12-13 06:40

I\'ve read around quite a bit but haven\'t found a definitive answer.

I have a class that looks like this:

    public class Foo() {

        private          


        
8条回答
  •  萌比男神i
    2020-12-13 07:02

    There is nothing inherently thread safe about a final static variable. Declaring a member variable final static only ensures that this variable is assigned to just once.

    The question of thread safety has less to do with how you declare the variables but instead relies on how you interact with the variables. So, it's not really possible to answer your question without more details on your program:

    • Do multiple threads modify the state of your sharedData variable?
    • If so, do you synchronize on all writes (and reads) of sharedData?

    Using a ConcurrentHashMap only guarantees that the individual methods of the Map are thread-safe, it doesn't make an operation such as this thread-safe:

    if (!map.containsKey("foo")) {
        map.put("foo", bar);
    }
    

提交回复
热议问题