I am trying to implement a thread safe cache Mapand I want the cached to Stringsbe lazily initialized. Here is my first pass on implementation:
Map
Strings
public class ExampleClass { private static final Map<String, String> CACHED_STRINGS = new HashMap<String, String>(); public String getText(String key) { String string = CACHED_STRINGS.get(key); if (string == null) { synchronized (CACHED_STRINGS) { string = CACHED_STRINGS.get(key); if (string == null) { string = createString(); CACHED_STRINGS.put(key, string); } } } return string; } }
Netbeans " ", . , , , , , , new synchronized. new, , , . HashMap? , createString()?
new
synchronized
HashMap
createString()
, , .
get put. , .
get
put
, , :
public T get(string key){ Entry e = findEntry(key); return e.value; } public void put(string key, string value){ Entry e = addNewEntry(key); //danger for get while in-between these lines e.value = value; } private Entry addNewEntry(key){ Entry entry = new Entry(key, ""); //a new entry starts with empty string not null! addToBuckets(entry); //now it findable by get return entry; }
get null, put , getText .
null
getText
, , . .
, , JIT , , , , .
- Map.computeIfAbsent(), , .
Map.computeIfAbsent()
Map<String, String> cache = new ConcurrentHashMap<>( ); cache.computeIfAbsent( "key", key -> "ComputedDefaultValue" );
Javadoc: , , . , . , , .
Concurrency .
.
, . HashMap , - , , .
- - Guava Cache Cache Loader, concurrency . , .
, ConcurrentHashMap .
Recap: /; , , .
: map.get() put(), , , , . - , , (, , , ). , .
guava: , , , . , "if null" , , , , . ( , -, factory , , , , ).
Source: https://habr.com/ru/post/1627799/More articles:How to get all CloudKit entries created by current user? - iosHow to use php curl to send push messages in Firefox - phpDo the advantages and disadvantages of somehow conditional std :: atomic_thread_fence get? - c ++There are no packages lib32z1, lib32ncurses5, lib32stdc ++ 6 available in centos - androidSpark: force two RDDs [Key, Value] with shared partitions using a custom delimiter - shuffleWhat is a back shell? - shellSet a class variable from a module - ruby | fooobar.comReplace a few dots in a string with a different character, but with the same sum - stringPandas and Rolling_Mean offset (average daily volume calculation) - pythonHow to avoid setters using symfony with admin panel maker? - symfonyAll Articles