Alternative to DCL with Maps

Hi,

"Double-Check Locking" with HashMap is broken, but it has (not working) features we may need to reproduce:

1. Efficient get if a value is already present in the map.

2. Single value creation (if value is absent).

The public V putIfAbsent(K key, V value) method in ConcurrentHashMap seems strange at first since it requires an instance of the value you want to retreive (and this value creation may be costly).

So, how to implement an efficient alternative to DCL ?

First, I could think about a simple synchronized method:

...

privatefinal Map<K, V> cache =new HashMap<K, V>();

...

publicsynchronized V get(K key){

V value = cache.get(key);

if (value ==null){

value =new ...;// create fully initialized value

cache.put(key, value);

}

return value;

}

Actually, DCL what created to avoid exactly this kind of code, but modern JVMs (5 and even more 6) seem to implement synchronized methods efficiently.

Second, I could use ConcurrentHashMap this way:

privatefinal ConcurrentHashMap<K, V> cache =new ConcurrentHashMap<K, V>();

...

public V get(K key){

V value = cache.get(key);

if (value ==null){

value =new ...;// create fully initialized value

value = cache.putIfAbsent(key, value);

}

return value;

}

This code does not prevent multiple value creations but it ensures that only one instance is put in the map and returned to all calling threads.

Third, I could extend ConcurrentHashMap with a kind of "if-absent" value creator:

publicinterface ValueCreator<V>{

public V create();

}

publicclass Cache<K, V>extends ConcurrentHashMap<K, V>{

public V putIfAbsent(K key, ValueCreator<V> creator){

// complicated code since we have to re-implement Segment.put(...)

}

}

This last code is not only complicated but potentially dangerous since we don't know what is done in ValueCreator.create (what happens if the create method tries indirectly to access the cache itself?)

I would really appreciate if some concurrency guru could give me good hints about those recurrent questions:

1. What about synchronized performances in Java 5/6 ?

2. Are there better solutions for DCL alternatives ?

Regards,

Franck.

.

[3703 byte] By [franck.wolffa] at [2007-11-27 2:44:49]
# 1
Read 13.2 and 16.2.4 of _Java Concurrency in Practice_(Goetz et al, Addison-Wesley).
hiwaa at 2007-7-12 3:11:47 > top of Java-index,Core,Core APIs...