multithreading - Which Java collection should I use to implement a thread-safe cache? -
I'm looking to apply a simple cache without doing a lot of work (naturally). It seems that one of the standard Java archives should be sufficient, with a little extra work. Specifically, I am storing responses from a server, and the keys can be either a hash code generated from either the URL string or the URL.
I originally thought I was a weak Hasham
, but it seems that the method forces me to manage those objects that I want to keep , And I do not manage strong references to any object, should I try the ConcurrentHashMap
instead of the SoftReference
values? Or will they be very aggressively cleansed?
Now I'm looking at the LinkedHashMap
class with some modifications it looks promising for an MRU cache. Any other suggestions?
Whatever collection I use should I sort out the LRU values manually, or can I rely on the bias against retrieving access items recently?
FYI, I am developing on Android, so I do not want to import any third party libraries. I am working with very small piles (16 to 24 MB), VM probably Curious to retrieve resources. I think that GC will be aggressive.
If you have SoftReference
-based keys, VM's recently accessed objects Contrary to prejudice (strongly), it will be very difficult to determine caching semantics - there is only one guarantee that a softrefer gives you (on weakening) is that will to OutOfMemoryError
before it is deleted. It is completely legal that a JVM implementation will treat them equally with the WEEK references, on which you can end up with a cache, which does not cache anything.
I do not know how things work on Android, but Sun's recent JVM with SoftRefLRUPolicyMSPerMB can increase the soft reference behavior with command line options, which determine the number of milliseconds That will be maintained for a soft-accessable object, per MB free memory per heap. As you can see, it will be difficult to achieve the behavior of any lifestyle according to any expectation, with added pain that this setting is global for all soft references in VM and isolated for the use of different sections Can not be done. Softarerens (chances are, each experiment will require different criteria).
The simplest way to make LRU cache is by expanding Lindahashim. Since you need thread-protection, the easiest way to get started is to use an example of safe class to ensure safe concurrent behavior.
Be careful of time pre-optimization - unless you need to have much more throughput, theoretically sub-upper overhead is not likely to be a problem. And good news - If profiling shows that due to the heavy lock you are performing at slow speed, then you will have enough information about the runtime usage of your cache, you may have a suitable lockless option (perhaps possibly < / P>
Comments
Post a Comment