public class PerThreadCache
extends java.lang.Object
implements java.lang.AutoCloseable
ThreadLocal
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-safe get
and put
methods. Once the
value is retrieved through get
there is not thread-safety anymore - apart from the
retrieved object guarantees. Depending on the implementation of CurrentUser
, 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, while CurrentUser
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 the Supplier
after that.
Modifier and Type | Class and Description |
---|---|
static class |
PerThreadCache.Key<T>
Unique key for key-value mappings stored in PerThreadCache.
|
Modifier and Type | Method and Description |
---|---|
void |
close() |
static PerThreadCache |
create() |
static PerThreadCache |
get() |
<T> T |
get(PerThreadCache.Key<T> key,
java.util.function.Supplier<T> loader)
Returns an instance of
T that was either loaded from the cache or obtained from the
provided Supplier . |
static <T> T |
getOrCompute(PerThreadCache.Key<T> key,
java.util.function.Supplier<T> loader) |
public static PerThreadCache create()
public static PerThreadCache get()
public static <T> T getOrCompute(PerThreadCache.Key<T> key, java.util.function.Supplier<T> loader)
public <T> T get(PerThreadCache.Key<T> key, java.util.function.Supplier<T> loader)
T
that was either loaded from the cache or obtained from the
provided Supplier
.public void close()
close
in interface java.lang.AutoCloseable