What makes usage volatile when using java.util.concurrent.Concurrent * containers?

The question arose when I saw this code:

private static volatile ConcurrentHashMap<String, String> cMap = null;
static {
    cMap = new ConcurrentHashMap<String, String>();
}

It seems to me that volatility is redundant, since the ConcurrentHashMap container , which according to JavaDoc already has synchronized puts , DUH, a class that uses cMap , and does not have any configuration or receiving methods.

The only thing I see in volatile is that I would like to set cMap to reference a new object in the near future, these reads and writes will be synchronized.

Did I miss something?

+3
source share
4 answers

The modifier volatilehas nothing to do with the class in question - it applies only to the variable cMap. This only affects how the thread retrieves or changes the value of this variable. By the time you typed the methods on the specified object, you were beyond the scope of bailiwick volatile.

As you say, it basically ensures that all threads are guaranteed to see value changes cMap(i.e. refer to another map).

This may be a good idea - or it may not be, depending on what the rest of the code does. If you can do this final, for example, you will not need volatile...

+7
source

, .

, , (.. / )

, . .

. JLS3 $12.4.2:

:

  • (§14.19) , .
+5

cMap volatile , . AFAIK , , null .

[]. @irreputable (, Java Concurrency , 3.5.3), : JVM , JVM. volatile . [/Update]

OTOH final ( , static) .

, volatile , . , .

+2

You declare cMap volatile only when its value changes. Announcing that it is volatile, it does not say anything about objects stored on the map.

If cMap modifies all threads, you will need to see the new current CHM value. However, I highly recommend cMap to be final. A non-finite static variable can be dangerous.

+1
source

Source: https://habr.com/ru/post/1763809/


All Articles