Is double locking check performed with final card in Java?

I am trying to implement a thread safe cache Mapand I want the cached to Stringsbe lazily initialized. Here is my first pass on implementation:

public class ExampleClass {

    private static final Map<String, String> CACHED_STRINGS = new HashMap<String, String>();

    public String getText(String key) {

        String string = CACHED_STRINGS.get(key);

        if (string == null) {

            synchronized (CACHED_STRINGS) {

                string = CACHED_STRINGS.get(key);

                if (string == null) {
                    string = createString();
                    CACHED_STRINGS.put(key, string);
                }
            }
        }

        return string;
    }
}

Netbeans " ", . , , , , , , new synchronized. new, , , . HashMap? , createString()?

+4
4

, , .

get put. , .

, , :

public T get(string key){
    Entry e = findEntry(key);
    return e.value;
}

public void put(string key, string value){
    Entry e = addNewEntry(key);
    //danger for get while in-between these lines
    e.value = value;
}

private Entry addNewEntry(key){
   Entry entry = new Entry(key, ""); //a new entry starts with empty string not null!
   addToBuckets(entry); //now it findable by get
   return entry; 
}

get null, put , getText .

, , . .

, , JIT , , , , .

+4

- Map.computeIfAbsent(), , .

Map<String, String> cache = new ConcurrentHashMap<>(  );
cache.computeIfAbsent( "key", key -> "ComputedDefaultValue" );

Javadoc: , , . , . , , .

+3

:

Concurrency .

.

, , .

, , .

, . HashMap , - , , .

- - Guava Cache Cache Loader, concurrency . , .

0

, ConcurrentHashMap .

Recap: /; , , .

: map.get() put(), , , , . - , , (, , , ). , .

guava: , , , . , "if null" , , , , . ( , -, factory , , , , ).

0

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


All Articles