What are the considerations when GuavaCache returns Null in Java
This article introduces the relevant knowledge of "what are the matters needing attention when GuavaCache returns Null in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
There are still many scenarios where Guava is used in actual Java back-end projects, such as current limiting, caching, container operations, and so on. There are many practical utility classes. Here we record a problem when using GuavaCache to return null.
i. Commonly used posture
@ Testpublic void testGuava () {LoadingCache cache = CacheBuilder.newBuilder () .build (new CacheLoader () {@ Override public String load (String key) throws Exception {if ("hello" .equals (key)) {return "word";} return null;}}); String word = cache.getUnchecked ("hello"); System.out.println (word) System.out.println (cache.getUnchecked ("word"));}
The above is a very simple test case. It should be noted that the execution of cache.get ("word") does not return null as the overdue one, but throws an exception.
Word
Com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key word.
At com.google.common.cache.LocalCache$Segment.getAndRecordStats (LocalCache.java:2287)
...
It can be seen from the exception description that null is not allowed to be returned, which was not noticed before, so in the case of null, either define a tag to indicate that it does not exist, or actively throw an exception in the load () method. Note when using it, through the use of the exception, you can do the following
Public class NoVlaInGauvaException extends Exception {public NoVlaInGauvaException (String msg) {super (msg);} @ Override public synchronized Throwable fillInStackTrace () {return this;}}
Description: why override the fillInStackTrace method
For this kind of cache misses, generally speaking, there is no need to pay attention to the complete stack information, there is only no data, which can save a little bit of performance (of course, there will be symptoms only when it is thrown frequently)
The second is the difference between get and getUnchecked.
Get requires display to deal with exception status
GetUnchecked is generally a scenario in which you can confirm that there will be no problem. Call the
After the transformation, our cache is as follows
LoadingCache cache = CacheBuilder.newBuilder () .build (new CacheLoader () {@ Override public String load (String key) throws Exception {if ("hello" .equals (key)) {return "word";} throw new NoVlaInGauvaException ();}}); "what are the considerations for returning Null in GuavaCache in Java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!