Class PerThreadCache
- All Implemented Interfaces:
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.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final class
Unique key for key-value mappings stored in PerThreadCache. -
Method Summary
Modifier and TypeMethodDescriptionvoid
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 Details
-
create
-
get
-
getOrCompute
-
get
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
-