Create a thread-safe cache
Procedure
-
Decide the key and value types
for your cache based on input data.
For example, you need to pass a
Stringand get anIntegerback from the cache. -
Construct a new cache.
For example:
// A cache of string values to their upper case values var myCache = new Cache<String, String>( "My Uppercase Cache", 100, \ s -> s.toUpperCase() ) -
To use the cache, call the get method and pass the input value, which is the key. If the value is in the cache,
getreturns the value from the cache. If the value is not cached, Gosu calls the block and calculates the value from the key and then caches the result.For example:print(myCache.get("Hello world") print(myCache.get("Hello world")This code prints:
"HELLO WORLD" "HELLO WORLD"
Results
In this example, the first call of the get method calls the block to generate the uppercase value. On the second call of the get method, the value is the same but Gosu uses the cached value.
