The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed to use a WeakHashMap
or WeakReference
and how was it used?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
This blog post demonstrates the use of both classes: Java: synchronizing on an ID. The usage goes something like this:
IdMutextProvider provides id-based objects to synchronize on. The requirements are:
This is achieved using an internal storage map of type:
The object is both key and value. When nothing external to the map has a hard reference to the object, it can be garbage collected. Values in the map are stored with hard references, so the value must be wrapped in a WeakReference to prevent a memory leak. This last point is covered in the javadoc.
One real world use I had for WeakReferences is if you have a single, very large object that's rarely used. You don't want to keep it in memory when it's not needed; but, if another thread needs the same object, you don't want two of them in memory either. You can keep a weak reference to the object somewhere, and hard references in the methods that use it; when the methods both finish, the object will be collected.
I did a google code search for "new WeakHashMap()".
I got a bunch of matches from the GNU classpath project and
you can use weakhashmap to implement a resource-free caching for expansive object creation.
but note that it is not desireable to have mutable objects. i used it to cache query results (which take about 400 ms to execute) to a text-search engine, which is rarely updated.