Does ConcurrentMap.remove () provide a predefined event before get () returns null?

Are actions in the thread expected before the call ConcurrentMap.remove()— before actions after viewing the deletion from another thread?

The documentation talks about objects placed in the collection:

Actions in a stream before placing an object in any parallel collection will occur - before actions after accessing or removing this element from the collection in another stream.

Code example:

{
    final ConcurrentMap map = new ConcurrentHashMap();
    map.put(1, new Object());

    final int[] value = { 0 };

    new Thread(() -> {
        value[0]++;
        value[0]++;
        value[0]++;
        value[0]++;
        value[0]++;

        map.remove(1); // A

    }).start();

    new Thread(() -> {
        if (map.get(1) == null) { // B
            System.out.println(value[0]); // expect 5
        }

    }).start();
}

Is A in the case where a connection occurs with B? Therefore, if the program only, if ever, prints 5?

+4
source share
4 answers

concurrency , .

-, null, , , , , - , , , , .

, , , , , null, , . , , , , . .

: map.put(1, new Object()) , , null 1, , , , .

Java 8s ConcurrentHashMap :

Retrievals , . ( "" ( ) , .)

null.

, (Java 8) ConcurrentHashMap , , volatile . , , , , .

+3

ConcurrentHashMap - , map.remove(1) , . map.get(1) , .

ConcurrentHashMap Java 7 , / .

ConcurrentSkipListMap , .

, , .

+1

, .

put() get() . . - get() get() remove(), put() put().

. . -. , get() , .

Intel , . Java , , .

+1

A B.

put. , B , A.

++ remove . volatile ; Map , . .

To my understanding, A could delete and be written back, then the last ++ will happen, and something like 4 will be printed in B. I would add volatileto the array. The card itself will be fine.

I am far from certain, but since I did not see the corresponding answer, I close my neck. (To get to know yourself.)

+1
source

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


All Articles