Java Visibility: Final Static Non-Thermal Collection Changes After Construction

I found the following snippet of code in luaj, and I began to doubt that if there is a chance that the changes made Mapafter it was created, it may not be visible to other threads, since there is no synchronization.

I know that since it is Mapdeclared final, its initialized values ​​after building are visible to other threads, but what about the changes that will happen after that.

Some may also realize that this class is not thread safe, since calling coerce in a multi-threaded environment may even cause an infinite loop in HashMap, but my question is not that.

public class CoerceJavaToLua {
    static final Map COERCIONS = new HashMap(); // this map is visible to all threads after construction, since its final

    public static LuaValue coerce(Object paramObject) {
        ...;
        if (localCoercion == null) {
            localCoercion = ...;
            COERCIONS.put(localClass, localCoercion); // visible?
        }
        return ...;
    }

    ...
}
+4
3

, Map . , COERCIONS ( , ), synchronized . , , .

(, ?)

+3

(, , TreeMap), HashMap , , , - ). , , , , .

, Map , , ( coersion , , ). , . , LuaJ.

+2

:

// Synchronized (since Java 1.2)
static final Map COERCIONS = Collections.synchronizedMap(new HashMap());

// Concurrent (since Java 5)
static final Map COERCIONS = new ConcurrentHashMap();

Each of them has its pros and cons.

ConcurrentHashMappro is not a lock. Con is that operations are not atomic, for example. a Iteratorin one thread, and a call putAllin another will allow the iterator to see some added values.

0
source

All Articles