Groovy memoized annotation protectedCacheSize usage
This documentation mentions:
By default, the size of the cache is unlimited and no cache result is protected from garbage collection.
Setting a protectedCacheSize>0 would create an unlimited cache with some results protected.
Setting maxCacheSize>0 would create a limited cache but without any protection from garbage protection.
Setting both would create a limited, protected cache.
So a use case would be if you e.g. have a memory intensive application that might run the risk of the cache being garbage collected too often or deeply, then using the protectedCacheSize
can forcibly protect a certain number of the most recently used cache entries from garbage collection.
This will make even more sense if the cached values are expensive to compute and the protectedCacheSize
is not too high as to prevent the GC from regaining needed memory.
Digging a bit deeper the AST for the @Memoized
annotation is handled by the groovy.transform.MemoizedASTTransformation.java which converts the method call to a Closure
.
Depending on the max and protected args being 0 or not different memoize
methods are then called on the Closure, see the implementation for more detail (scroll down for the three other memoize methods).