Java高性能集合类 ConcurrentLinkedHashMap 可以实现LRU缓存策略

ConcurrentLinkedHashMap是java.util.LinkedHashMap的一个高性能实现。主要用于软件缓存。

ConcurrentLinkedHashMap 是google团队提供的一个容器。它有什么用呢?其实它本身是对
ConcurrentHashMap的封装,可以用来实现一个基于LRU策略的缓存。详细介绍可以参见  
http://code.google.com/p/concurrentlinkedhashmap

https://github.com/ben-manes/concurrentlinkedhashmap

  1. import java.util.Map;
  2. import java.util.concurrent.ConcurrentMap;
  3. import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
  4. import com.googlecode.concurrentlinkedhashmap.EvictionListener;
  5. import com.googlecode.concurrentlinkedhashmap.Weighers;
  6. public class Test {
  7. public static void main(String[] args) {
  8. //test001();
  9. test002();
  10. }
  11. private static void test001() {
  12. EvictionListener<String, String> listener = new EvictionListener<String, String>() {
  13. @Override
  14. public void onEviction(String key, String value) {
  15. System.out.println( "Evicted key=" + key + ", value=" + value);
  16. }
  17. };
  18. ConcurrentMap<String, String> cache = new ConcurrentLinkedHashMap.Builder<String, String>()
  19. .maximumWeightedCapacity( 10).listener(listener).build();
  20. for ( int i = 0; i < 150; i++) {
  21. int j = 1024;
  22. j = j + i;
  23. cache.put(String.valueOf(j), "nihao" + i);
  24. }
  25. for (Map.Entry<String, String> entry : cache.entrySet()) {
  26. String key = entry.getKey();
  27. String value = entry.getValue();
  28. System.out.println(key + "====" + value);
  29. }
  30. System.out.println(cache.get( "1025"));
  31. cache.remove( "1026");
  32. }
  33. /**
  34. ConcurrentLinkedHashMap 是google团队提供的一个容器。它有什么用呢?其实它本身是对
  35. ConcurrentHashMap的封装,可以用来实现一个基于LRU策略的缓存。详细介绍可以参见
  36. http://code.google.com/p/concurrentlinkedhashmap
  37. */
  38. private static void test002() {
  39. ConcurrentLinkedHashMap<Integer, Integer> map = new ConcurrentLinkedHashMap.Builder<Integer, Integer>()
  40. .maximumWeightedCapacity( 2).weigher(Weighers.singleton())
  41. .build();
  42. map.put( 1, 1);
  43. map.put( 2, 2);
  44. map.put( 3, 3);
  45. System.out.println(map.get( 1)); // null 已经失效了
  46. System.out.println(map.get( 2));
  47. }

猜你喜欢

转载自blog.csdn.net/u011955252/article/details/80940373
今日推荐