When I was learning the Hystrix framework recently, I saw a piece of code that was very interesting, and the code was as follows:
Code Listing 1-1
public class Internmap<k, v> {
private final concurrentmap<k, v> storage = new Concurrenthashmap<k, V&G t; ();
Private final valueconstructor<k, v> Valueconstructor;
Public interface Valueconstructor<k, v> {
V Create (K key);
}
Public V interned (K key) {
V Existingkey = Storage.get (key);
V NewKey = null;
if (Existingkey = = null) {
NewKey = valueconstructor.create (key);
Existingkey = Storage.putifabsent (key, NewKey);
}
Return existingkey!= null? Existingkey:newkey
}
}
Omitted some of the non-attention code ...
Valueconstructor is a functional interface, the function of which is to get value value of the key, JDK8 introduced new features.
Focus on the above interned method: first to determine whether the value of the key already exists: if it does not exist, then through the valueconstructor to generate a new value, and stored in the storage. Finally returns the value that already exists
The logic is very simple, but the code above is very complex, feeling a bit verbose, the general writing is as follows:
Code Listing 1-2
Public V interned (K key) {
V existingvalue = Storage.get (key);
if (Existingvalue = = null) {
Existingvalue = valueconstructor.create (key);
Storage.put (key, Existingvalue);
return existingvalue;
}
Careful analysis of the above simple writing, there is a thread-safety problem. Because there is no synchronization, two threads may enter the IF statement block at the same time, causing each thread to get a different existingvalue, which is clearly not desirable.
Looking back at code 1-1, we understand the author's deep meaning. The thread-safe Putifabsent method provided by Concurrenthashmap guarantees the thread safety of the storage deposit, while the Newkey, Existingkey (in fact, should be named NewValue, Existingvaule) Two-thread variable value judgments are returned to ensure the atomic nature of the entire method operation.
This thread-safe approach, without the use of synchronous code blocks, such as inefficient synchronization, is indeed an efficient way to implement the map of the atomic update, and have to admire the author's thoughtful.
Finally, I want to ask the question: Yuan Fang, what do you think?