Class PerThreadCache
- java.lang.Object
-
- com.google.gerrit.server.cache.PerThreadCache
-
- All Implemented Interfaces:
AutoCloseable
public class PerThreadCache extends Object implements AutoCloseable
Caches object instances for a request asThreadLocal
in the serving thread.This class is intended to cache objects that have a high instantiation cost, are specific to the current request and potentially need to be instantiated multiple times while serving a request.
This is different from the key-value storage in
CurrentUser
:CurrentUser
offers a key-value storage by providing thread-safeget
andput
methods. Once the value is retrieved throughget
there is not thread-safety anymore - apart from the retrieved object guarantees. Depending on the implementation ofCurrentUser
, it might be shared between the request serving thread as well as sub- or background treads.In comparison to that, this class guarantees thread safety even on non-thread-safe objects as its cache is tied to the serving thread only. While allowing to cache non-thread-safe objects, it has the downside of not sharing any objects with background threads or executors.
Lastly, this class offers a cache, that requires callers to also provide a
Supplier
in case the object is not present in the cache, whileCurrentUser
provides a storage where just retrieving stored values is a valid operation.To prevent OOM errors on requests that would cache a lot of objects, this class enforces an internal limit after which no new elements are cached. All
get
calls are served by invoking theSupplier
after that.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
PerThreadCache.Key<T>
Unique key for key-value mappings stored in PerThreadCache.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
close()
static PerThreadCache
create()
static PerThreadCache
get()
<T> T
get(PerThreadCache.Key<T> key, Supplier<T> loader)
Returns an instance ofT
that was either loaded from the cache or obtained from the providedSupplier
.static <T> T
getOrCompute(PerThreadCache.Key<T> key, Supplier<T> loader)
-
-
-
Method Detail
-
create
public static PerThreadCache create()
-
get
public static PerThreadCache get()
-
getOrCompute
public static <T> T getOrCompute(PerThreadCache.Key<T> key, Supplier<T> loader)
-
get
public <T> T get(PerThreadCache.Key<T> key, Supplier<T> loader)
Returns an instance ofT
that was either loaded from the cache or obtained from the providedSupplier
.
-
close
public void close()
- Specified by:
close
in interfaceAutoCloseable
-
-