[concurrency-interest] Double Checked Locking and String

Shevek shevek at anarres.org
Thu Sep 7 14:58:05 EDT 2017


You're all quite right, of course. Simplifying the example from my 
application code blinded me to the obvious. Thank you immensely.

As for what I'm trying to do: Generate unique textual representation per 
IR symbol in the output stage of a multi-threaded compiler, so the 
compute function has to look at another collection to make sure a string 
name isn't yet issued for use.

S.

On 09/07/2017 04:05 AM, Norman Maurer wrote:
> Why not just use computeIfAbsent(...) ?
> 
> https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentMap.html#computeIfAbsent-K-java.util.function.Function-
> 
> Am 07.09.2017 um 13:01 schrieb Shevek <shevek at anarres.org 
> <mailto:shevek at anarres.org>>:
> 
>> Is the following code correct:
>>
>> Map<T, String> m = new ConcurrentHashMap<>();
>>
>> public void getString(T t) {
>>    String out = m.get(t);
>>    if (out != null)
>>        return out;
>>    synchronized (m) {
>>        out = m.get(t);
>>        if (out == null) {
>>            out = String.valueOf(t); // all fields final.
>>            m.put(t, out);
>>        }
>>    }
>>    return out;
>> }
>>
>> The principle being that yes it's a double-checked lock, but the field 
>> in String is final. Is that enough to cause the publication to be 
>> safe? I _think_ this is an instance of FinalWrapperFactory from 
>> https://shipilev.net/blog/2014/safe-public-construction/ but it may be 
>> that the system thinks that there's another read-path for the variable 
>> via the Map, and that makes it not be a safe publication.
>>
>> Thank you.
>>
>> S.
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu 
>> <mailto:Concurrency-interest at cs.oswego.edu>
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest


More information about the Concurrency-interest mailing list