Advertisement
Guest User

Untitled

a guest
Apr 28th, 2014
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. package com.samir;
  2.  
  3.  
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6. import java.util.LinkedHashMap;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import android.graphics.Bitmap;
  10. import android.util.Log;
  11.  
  12. public class MemoryCache {
  13.  
  14. private static final String TAG = "MemoryCache";
  15. private Map<String, Bitmap> cache=Collections.synchronizedMap(
  16. new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
  17. private long size=0;//current allocated size
  18. private long limit=1000000;//max memory in bytes
  19.  
  20. public MemoryCache(){
  21. //use 25% of available heap size
  22. setLimit(Runtime.getRuntime().maxMemory()/4);
  23. }
  24.  
  25. public void setLimit(long new_limit){
  26. limit=new_limit;
  27. Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
  28. }
  29.  
  30. public Bitmap get(String id){
  31. try{
  32. if(!cache.containsKey(id))
  33. return null;
  34. //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
  35. return cache.get(id);
  36. }catch(NullPointerException ex){
  37. ex.printStackTrace();
  38. return null;
  39. }
  40. }
  41.  
  42. public void put(String id, Bitmap bitmap){
  43. try{
  44. if(cache.containsKey(id))
  45. size-=getSizeInBytes(cache.get(id));
  46. cache.put(id, bitmap);
  47. size+=getSizeInBytes(bitmap);
  48. checkSize();
  49. }catch(Throwable th){
  50. th.printStackTrace();
  51. }
  52. }
  53.  
  54. private void checkSize() {
  55. Log.i(TAG, "cache size="+size+" length="+cache.size());
  56. if(size>limit){
  57. Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated
  58. while(iter.hasNext()){
  59. Entry<String, Bitmap> entry=iter.next();
  60. size-=getSizeInBytes(entry.getValue());
  61. iter.remove();
  62. if(size<=limit)
  63. break;
  64. }
  65. Log.i(TAG, "Clean cache. New size "+cache.size());
  66. }
  67. }
  68.  
  69. public void clear() {
  70. try{
  71. //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
  72. cache.clear();
  73. size=0;
  74. }catch(NullPointerException ex){
  75. ex.printStackTrace();
  76. }
  77. }
  78.  
  79. long getSizeInBytes(Bitmap bitmap) {
  80. if(bitmap==null)
  81. return 0;
  82. return bitmap.getRowBytes() * bitmap.getHeight();
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement