Note that there are some explanatory texts on larger screens.

plurals
  1. POIs this code a thread-safe one?
    primarykey
    data
    text
    <p>I want to process a flow of client requests. Each request has its special type. First I need to initialize some data for that type, and after this I can start processing the requests. When the client type comes for the first time, I just initialize the corresponding data. After this all the following requests of that type are processed using that data. </p> <p>I need to do this in a thread-safe manner.</p> <p>Here is a code I have written. Is it thread-safe?</p> <pre><code>public class Test { private static Map&lt;Integer, Object&gt; clientTypesInitiated = new ConcurrentHashMap&lt;Integer, Object&gt;(); /* to process client request we need to create corresponding client type data. on the first signal we create that data, on the second - we process the request*/ void onClientRequestReceived(int clientTypeIndex) { if (clientTypesInitiated.put(clientTypeIndex, "") == null) { //new client type index arrived, this type was never processed //process data for that client type and put it into the map of types Object clientTypeData = createClientTypeData(clientTypeIndex); clientTypesInitiated.put(clientTypeIndex, clientTypeData); } else { //already existing index - we already have results and we can use them processClientUsingClientTypeData(clientTypesInitiated.get(clientTypeIndex)); } } Object createClientTypeData(int clientIndex) {return new Object();} void processClientUsingClientTypeData(Object clientTypeData) {} } </code></pre> <p>From one hand, ConcurrentHashMap cannot produce map.put(A,B) == null two times for the same A. From the other hand, the assignment and comparisson operation is not thread-safe. </p> <p>So is this code is ok? If not, how can I fix it?</p> <p>UPDATE: I have accepted the answer of Martin Serrano because his code is thread-safe and it is not prone to double initialization issue. But I would like to note, that I have not found any isssues with my version, posted as an answer below, and my version does not require synchronization.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload