Class PerThreadCache

  • All Implemented Interfaces:
    AutoCloseable

    public class PerThreadCache
    extends Object
    implements AutoCloseable
    Caches object instances for a request as 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.