[concurrency-interest] Double Checked Locking and String

Shevek shevek at anarres.org
Thu Sep 7 07:01:21 EDT 2017

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.


More information about the Concurrency-interest mailing list