Idle to Nothing, with Java's soft reference to write a cottage cache

Source: Internet
Author: User

Idle to Nothing, with Java's soft reference to write a cottage cache Blog Category:
    • Java Basics
It is well known that references in Java are divided into Strongreference, SoftReference, WeakReference, Phantomreference. These kinds of references have different uses of the scene, usually we use the most frequent is the strongreference, that is to say the form of such a reference:

Object obj = new Object ();

such a reference is called a strong reference, and if the object does not have a reference to it, and the surviving thread cannot access it (for a garbage island), then he is recycled, and if the object is pointed to by a strong reference and the memory is exhausted, the object is not reclaimed by the Oom garbage collector.

For SoftReference, it is less stringent for GC recycling, and if the current strongest reference to an object is a soft reference, and the JVM has sufficient memory, the garbage collector will not recycle the object. The GC reclaims the object pointed to by the soft reference only when the memory is tight, and from this we can see that the soft reference could be used to do some caching, better with the LRU strategy. Today I will write a play.

Java code
    1. The code is as follows:
Java code
  1. Package com.blackbeans.example;
  2. Import java.lang.ref.Reference;
  3. Import Java.lang.ref.ReferenceQueue;
  4. Import java.lang.ref.SoftReference;
  5. Import Java.util.HashMap;
  6. /**
  7. *
  8. * @author Blackbeans
  9. * @param <K>
  10. * @param <T>
  11. */
  12. Public class Referencecache<k,t> {
  13. private hashmap<k, innerreference<k,t>> cachedreference = new hashmap<k, innerreference<k,t  >> (1024);
  14. Private final referencequeue<t> referencequeue;
  15. Private final objectnotfoundhandler<k,t> Existshandler;
  16. /** 
  17. * Processors that are not in the default cache
  18. * @author Blackbeans
  19. *
  20. * @param <K>
  21. * @param <T>
  22. */
  23. private static class defaultobjectnotfoundhandler<k,t> implements Objectnotfoundhandler<k, t>
  24. {
  25. @Override
  26. Public T queryandcached (K key) {
  27. //TODO auto-generated method stub
  28. return null;
  29. }
  30. }
  31. /** 
  32. * Processors that are not in the cache
  33. * @author Blackbeans
  34. *
  35. * @param <K>
  36. * @param <T>
  37. */
  38. public Static interface objectnotfoundhandler<k,t>
  39. {
  40. Public T queryandcached (K key);
  41. }
  42. private static class innerreference<k,t> extends softreference<t>{
  43. Private final K key;
  44. Public innerreference (K key,t reference,referencequeue<t> queue) {
  45. super (Reference,queue);
  46. This.key = key;
  47. }
  48. Public K GetKey ()
  49. {
  50. return This.key;
  51. }
  52. }
  53. Public Referencecache (objectnotfoundhandler<k,t> handler)
  54. {
  55. this.referencequeue = new referencequeue<t> ();
  56. This.existshandler = Handler = = null?  New Defaultobjectnotfoundhandler<k,t> (): handler;
  57. }
  58. Public Referencecache ()
  59. {
  60. This (null);
  61. }
  62. public void cachedreference (K key,t Reference)
  63. {
  64. /** 
  65. * Clears objects that are soft-referenced and has been recycled reference
  66. */
  67. Cleanreference (key);
  68. if (! This.cachedReference.containsKey (key))
  69. {
  70. this.cachedReference.put (Key, new Innerreference<k,t> (key,reference, this.referencequeue));
  71. }
  72. }
  73. Public T getreference (K key) {
  74. T obj = null;
  75. if (This.cachedReference.containsKey (key)) {
  76. obj = this.cachedReference.get (key). get ();
  77. }
  78. if (null = = obj)
  79. {
  80. /** 
  81. * Soft references to objects are recycled and cached by the soft reference
  82. */
  83. obj = this.existsHandler.queryAndCached (key);
  84. this.cachedreference (key, obj);
  85. return obj;
  86. }
  87. return obj;
  88. }
  89. @SuppressWarnings ("unchecked")
  90. private void Cleanreference (K key) {
  91. //Priority check if key corresponds to soft-referenced object being recycled
  92. if (this.cachedReference.containsKey (key)
  93. && This.cachedReference.get (key). Get () = = null)
  94. This.cachedReference.remove (key);
Java code
  1. <span style="WHITE-SPACE:PRE;"  > </span>t obj = null;
  2. //Remove the key if the soft-referenced object that corresponds to the current key is recycled
  3. reference<?  extends t> reference = null;
  4. While ((reference = This.referenceQueue.poll ()) = null)
  5. {
  6. obj = Reference.get ();
  7. if (obj = = null)
  8. {
  9. This.cachedReference.remove (((innerreference<k, t>) reference). GetKey ());
  10. }
  11. }
  12. }
  13. public void Clearallobject ()
  14. {
  15. this.cachedReference.clear ();
  16. System.GC ();
  17. }
  18. }

in the entire implementation by putting the object's reference into a key-> soft reference map I defined, and then each time I get the object from the cache, the key is used to query the map to get the soft reference of the object, and if it exists, it tries to get the object by soft reference, if it does not exist, The object that the soft reference points to is recycled, then we go back to call the built-in handler, regenerate an object, and cache the soft reference of the object.

In my implementation I provide the user with a processing handler when the object is recycled, trying to guide the user through this handler to reconstruct the object, the cache object, the flexibility is still very large.

The disadvantage is that if the soft-referenced cache is more perfect with the LRU policy, a processor for the LRU is provided for the user to customize the LRU policy. In fact, it is very simple to replace the HashMap with Linkedhashmap to implement the Removeeldest method, and call the custom LRU processor in the method is OK.

To reduce the overhead, I cleaned out the failed soft references every time the cache was made. Maybe someone will ask why is there a referencequeue? In fact, after the object referenced by the soft reference is recycled, imagine that the object soft reference is being recycled, but you have introduced another object softreference, take away one is not to leave another, so will not, soft reference object is recycled, The soft reference itself is added to this queue, waiting to be recycled. By facilitating this queue to get a soft reference to an out-of-date soft reference in the map.

At this point, the said also said, should not say also said, the end is very abrupt, please forgive me!

Reprint: http://blackbeans.iteye.com/blog/1039464

Idle to Nothing, with Java's soft reference to write a cottage cache

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.