I have a
ConcurrentMap<String, SoftReference<X>> map = new ConcurrentHashMap<String, SoftReference<X>>();
and would like the key/value pair removed from the map when the referent of the SoftReference is GC’ed.
How do I go about achieving this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Key/value pair will not be removed, when the referent of the SoftReference is GC’ed.
THe following program shows the result.
And the result is:
As it shows, the key/value pair is not removed, when the refent is GC’ed.
You can implement your own RefenceQueue and SoftReference to achive your target, and override RefenceQueue’s poll method, in which you can do your own job, like this:
Then replace SoftReference and SoftReferenceMonitor with SoftReferenceMonitor and CustomizedSoftReference respectively, and run the program. The result is:
Now the key/value pair has been removed.
Besides, you can use another thread to construct the SoftReferenceMonitor instance and monitor the SoftReference.
Hope this useful.