Guava is Google's Java class Library, the function is very powerful, the following is the local memory Cache tool class instance, the first time by calling get (key), will call load to get the value, when called again, we find that it is called directly from the cache, according to MaximumSize set the cache size, When the size exceeds the limit, the furthest data is removed from the cache. Examples are as follows.
Guava Cahche instance, through Loadingcache
public class Main {static map<string, integer> Map = new hashmap<string, integer> (); public static Integer Getvaluebykey (String key) {System.out.println ("via key:" + key + "Get value"); return Map.get (key); } @Test public void Loadingcache () throws Executionexception {map.put ("Key1", 1); Map.put ("Key2", 2); Map.put ("Key3", 3); loadingcache<string, integer> cahcebuilder = Cachebuilder.newbuilder (). MaximumSize (2). Build (New Cach Eloader<string, integer> () {@Override public Integer load (String key) throws Exception {return Getvaluebykey (key); } }); System.out.println (Cahcebuilder.get ("Key1")); System.out.println (Cahcebuilder.get ("Key2")); System.out.println (Cahcebuilder.get ("Key3")); System.out.println (Cahcebuilder.get ("Key1")); System.out.println (Cahcebuilder.get ("Key3")); Cahcebuilder.put ("Key1", 4); System.out.println (Cahcebuilder.get ("Key1")); }}
Operation Result:
Of course, there is another way to achieve this, using callable
The following methods can be used to remove values.
Cache.invalidate ("Key1"); Cache.invalidateall ();
The result shows that when a value of the same key is repeatedly obtained, call () is not executed, but is read from the buffer.
Cahcebuilder.refresh ("Key1"); method can refresh the key value
Cacheloader.reload (K, V) generates a new value
Cachebuilder.refreshafterwrite (Long, Timeunit) automatically refreshes cache after timeout
Cache instance of Guava Learning note