Cache and refence counting #820
-
Hello, we have a complex use case where we cache a value that has internal resources. The resources must not be freed until all users are done using the object. To accomplish this we use reference counting. When the object is added to the cache, we set the ref count to 1. The object imeplements AutoCloseable and decrements on each close. Also decrements when it is evicted from the cache (via eviction listener). That way when ref count is 0 the resources are released. The issue is that we need to increment the internal reference count when the object is obtained from the cache. Is there a hook/listener that would be invoked when the cache hands out the obeject that we could use? We can of course have a facade on top of the cacheable that increments the ref count, but it's not a very elegant solution. Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
The cache is best viewed as a bounded ConcurrentMap, so like The faq discusses a similar problem called pinning, where ref counted entries should not be evictable. To do that the counter can be modified within a Map computation, so that when the cache evaluates its expiration and weight those can be set to be disabled. You might find that useful or else a similar approach if you want the increment to be atomic with the entry (but as a cache write, this is more expensive than a lock-free read). |
Beta Was this translation helpful? Give feedback.
-
I'm looking to do something similar here. I want to save the cache entries to a file when the cache shuts down. How can I add an event to determine if the cache is shutting down? I have a singleton in front of the cache. I thought about using AutoCloseable and running code when it's shutting down. |
Beta Was this translation helpful? Give feedback.
The cache is best viewed as a bounded ConcurrentMap, so like
HashMap
your own logic would act as a facade above it rather than being the direct client api. If you simply need to increment a per-entry counter on access then that is trivial to do in your code and the library offering something doesn't add much value.The faq discusses a similar problem called pinning, where ref counted entries should not be evictable. To do that the counter can be modified within a Map computation, so that when the cache evaluates its expiration and weight those can be set to be disabled. You might find that useful or else a similar approach if you want the increment to be atomic with the entry (but as a ca…