JAVA 实现自定义的缓存实现

首先要了解下java1.6中的ConcurrentMap ,他是一个线程安全的Map实现,特别说明的是在没有特别需求的情况下可以用ConcurrentHashMap。我是想学习一下读写锁的应用,就自己实现了一个SimpleConcurrentHashMap.

  1. package com.cttc.cache.entity;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.HashSet;
  5. import java.util.Map;
  6. import java.util.Set;
  7. import java.util.concurrent.locks.Lock;
  8. import java.util.concurrent.locks.ReadWriteLock;
  9. import java.util.concurrent.locks.ReentrantReadWriteLock;
  10. public class SimpleConcurrentMap<K, V> implements Map<K, V> {
  11. final ReadWriteLock lock = new ReentrantReadWriteLock();
  12. final Lock r = lock.readLock();
  13. final Lock w = lock.writeLock();
  14. final Map<K, V> map;
  15. public SimpleConcurrentMap(Map<K, V> map) {
  16. this.map = map;
  17. if (map == null) throw new NullPointerException();
  18. }
  19. public void clear() {
  20. w.lock();
  21. try {
  22. map.clear();
  23. } finally {
  24. w.unlock();
  25. }
  26. }
  27. public boolean containsKey(Object key) {
  28. r.lock();
  29. try {
  30. return map.containsKey(key);
  31. } finally {
  32. r.unlock();
  33. }
  34. }
  35. public boolean containsValue(Object value) {
  36. r.lock();
  37. try {
  38. return map.containsValue(value);
  39. } finally {
  40. r.unlock();
  41. }
  42. }
  43. public Set<java.util.Map.Entry<K, V>> entrySet() {
  44. throw new UnsupportedOperationException();
  45. }
  46. public V get(Object key) {
  47. r.lock();
  48. try {
  49. return map.get(key);
  50. } finally {
  51. r.unlock();
  52. }
  53. }
  54. public boolean isEmpty() {
  55. r.lock();
  56. try {
  57. return map.isEmpty();
  58. } finally {
  59. r.unlock();
  60. }
  61. }
  62. public Set<K> keySet() {
  63. r.lock();
  64. try {
  65. return new HashSet<K>(map.keySet());
  66. } finally {
  67. r.unlock();
  68. }
  69. }
  70. public V put(K key, V value) {
  71. w.lock();
  72. try {
  73. return map.put(key, value);
  74. } finally {
  75. w.unlock();
  76. }
  77. }
  78. public void putAll(Map<? extends K, ? extends V> m) {
  79. w.lock();
  80. try {
  81. map.putAll(m);
  82. } finally {
  83. w.unlock();
  84. }
  85. }
  86. public V remove(Object key) {
  87. w.lock();
  88. try {
  89. return map.remove(key);
  90. } finally {
  91. w.unlock();
  92. }
  93. }
  94. public int size() {
  95. r.lock();
  96. try {
  97. return map.size();
  98. } finally {
  99. r.unlock();
  100. }
  101. }
  102. public Collection<V> values() {
  103. r.lock();
  104. try {
  105. return new ArrayList<V>(map.values());
  106. } finally {
  107. r.unlock();
  108. }
  109. }
  110. }

缓存对象CacheEntity.java为:

  1. package com.cttc.cache.entity;
  2. import java.io.Serializable;
  3. public class CacheEntity implements Serializable{
  4. private static final long serialVersionUID = -3971709196436977492L;
  5. private final int DEFUALT_VALIDITY_TIME = 20;//默认过期时间 20秒
  6. private String cacheKey;
  7. private Object cacheContext;
  8. private int validityTime;//有效期时长,单位:秒
  9. private long timeoutStamp;//过期时间戳
  10. private CacheEntity(){
  11. this.timeoutStamp = System.currentTimeMillis() + DEFUALT_VALIDITY_TIME * 1000;
  12. this.validityTime = DEFUALT_VALIDITY_TIME;
  13. }
  14. public CacheEntity(String cacheKey, Object cacheContext){
  15. this();
  16. this.cacheKey = cacheKey;
  17. this.cacheContext = cacheContext;
  18. }
  19. public CacheEntity(String cacheKey, Object cacheContext, long timeoutStamp){
  20. this(cacheKey, cacheContext);
  21. this.timeoutStamp = timeoutStamp;
  22. }
  23. public CacheEntity(String cacheKey, Object cacheContext, int validityTime){
  24. this(cacheKey, cacheContext);
  25. this.validityTime = validityTime;
  26. this.timeoutStamp = System.currentTimeMillis() + validityTime * 1000;
  27. }
  28. public String getCacheKey() {
  29. return cacheKey;
  30. }
  31. public void setCacheKey(String cacheKey) {
  32. this.cacheKey = cacheKey;
  33. }
  34. public Object getCacheContext() {
  35. return cacheContext;
  36. }
  37. public void setCacheContext(Object cacheContext) {
  38. this.cacheContext = cacheContext;
  39. }
  40. public long getTimeoutStamp() {
  41. return timeoutStamp;
  42. }
  43. public void setTimeoutStamp(long timeoutStamp) {
  44. this.timeoutStamp = timeoutStamp;
  45. }
  46. public int getValidityTime() {
  47. return validityTime;
  48. }
  49. public void setValidityTime(int validityTime) {
  50. this.validityTime = validityTime;
  51. }
  52. }

List缓存处理对象:

[java] view plaincopyprint?

  1. package com.cttc.cache.handler;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import com.cttc.cache.entity.CacheEntity;
  6. import com.cttc.cache.entity.SimpleConcurrentMap;
  7. public class CacheListHandler {
  8. private static final long SECOND_TIME = 1000;
  9. private static final SimpleConcurrentMap<String, CacheEntity> map;
  10. private static final List<CacheEntity> tempList;
  11. static{
  12. tempList = new ArrayList<CacheEntity>();
  13. map = new SimpleConcurrentMap<String, CacheEntity>(new HashMap<String, CacheEntity>(1<<18));
  14. new Thread(new TimeoutTimerThread()).start();
  15. }
  16. /**
  17. * 增加缓存对象
  18. * @param key
  19. * @param ce
  20. */
  21. public static void addCache(String key, CacheEntity ce){
  22. addCache(key, ce, ce.getValidityTime());
  23. }
  24. /**
  25. * 增加缓存对象
  26. * @param key
  27. * @param ce
  28. * @param validityTime 有效时间
  29. */
  30. public static synchronized void addCache(String key, CacheEntity ce, int validityTime){
  31. ce.setTimeoutStamp(System.currentTimeMillis() + validityTime * SECOND_TIME);
  32. map.put(key, ce);
  33. //添加到过期处理队列
  34. tempList.add(ce);
  35. }
  36. /**
  37. * 获取缓存对象
  38. * @param key
  39. * @return
  40. */
  41. public static synchronized CacheEntity getCache(String key){
  42. return map.get(key);
  43. }
  44. /**
  45. * 检查是否含有制定key的缓冲
  46. * @param key
  47. * @return
  48. */
  49. public static synchronized boolean isConcurrent(String key){
  50. return map.containsKey(key);
  51. }
  52. /**
  53. * 删除缓存
  54. * @param key
  55. */
  56. public static synchronized void removeCache(String key){
  57. map.remove(key);
  58. }
  59. /**
  60. * 获取缓存大小
  61. * @param key
  62. */
  63. public static int getCacheSize(){
  64. return map.size();
  65. }
  66. /**
  67. * 清除全部缓存
  68. */
  69. public static synchronized void clearCache(){
  70. tempList.clear();
  71. map.clear();
  72. System.out.println("clear cache");
  73. }
  74. static class TimeoutTimerThread implements Runnable {
  75. public void run(){
  76. while(true){
  77. try {
  78. checkTime();
  79. } catch (Exception e) {
  80. e.printStackTrace();
  81. }
  82. }
  83. }
  84. /**
  85. * 过期缓存的具体处理方法
  86. * @throws Exception
  87. */
  88. private void checkTime() throws Exception{
  89. //"开始处理过期 ";
  90. CacheEntity tce = null;
  91. long timoutTime = 1000L;
  92. //" 过期队列大小 : "+tempList.size());
  93. if(1 > tempList.size()){
  94. System.out.println("过期队列空,开始轮询");
  95. timoutTime = 1000L;
  96. Thread.sleep(timoutTime);
  97. return;
  98. }
  99. tce = tempList.get(0);
  100. timoutTime = tce.getTimeoutStamp() - System.currentTimeMillis();
  101. //" 过期时间 : "+timoutTime);
  102. if(0 < timoutTime){
  103. //设定过期时间
  104. Thread.sleep(timoutTime);
  105. return;
  106. }
  107. System.out.print(" 清除过期缓存 : "+tce.getCacheKey());
  108. //清除过期缓存和删除对应的缓存队列
  109. tempList.remove(tce);
  110. removeCache(tce.getCacheKey());
  111. }
  112. }
  113. }
时间: 2024-08-05 23:47:54

JAVA 实现自定义的缓存实现的相关文章

java 微信自定义菜单 java微信接口开发 公众平台 SSM redis shiro 多数据源

获取[下载地址]   QQ: 313596790官网 http://www.fhadmin.org/A 调用摄像头拍照,自定义裁剪编辑头像,头像图片色度调节B 集成代码生成器 [正反双向](单表.主表.明细表.树形表,快速开发利器)+快速表单构建器 freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面.建表sql脚本,处理类,service等完整模块C 集成阿里巴巴数据库连接池druid  数据库连接池  阿里巴巴的 druid.Druid在监控.可扩展性.稳定性和性能方面都

Spring Boot自定义Redis缓存配置,保存value格式JSON字符串

Spring Boot自定义Redis缓存,保存格式JSON字符串 部分内容转自 https://blog.csdn.net/caojidasabi/article/details/83059642 package springboot01cache.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; im

关于java中的本地缓存-总结概述

java中的本地缓存,工作后陆续用到,一直想写,一直无从下手,最近又涉及到这方面的问题了,梳理了一下.自己构造单例.guava.ehcache基本上涵盖了目前的大多数行为了.   为什么要有本地缓存? 在 系统中,有些数据,数据量小,但是访问十分频繁(例如国家标准行政区域数据),针对这种场景,需要将数据搞到应用的本地缓存中,以提升系统的访问效率,减 少无谓的数据库访问(数据库访问占用数据库连接,同时网络消耗比较大),但是有一点需要注意,就是缓存的占用空间以及缓存的失效策略. 为什么是本地缓存,而

Java的进程内缓存框架:EhCache (转)

EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. Ehcache缓存的特点: 1. 快速. 2. 简单. 3. 多种缓存策略 4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题 5. 缓存数据会在虚拟机重启的过程中写入磁盘 6. 可以通过RMI.可插入API等方式进行分布式缓存 7. 具有缓存和缓存管理器的侦听接口 8. 支持多缓存管理器实例,以及一个实例的多个缓存区域 9. 提供Hibernate的缓存实现 E

Java环境配置 数据库 缓存Redis Nosql MongoDB 安装

系统选择 centos 7.0 1.java安装篇 rpm -qa |grep java 检测是否java yum remove java-1.7.0-openjdk 使用命令删除java 到oracle官方下载java安装包 rpm -ivh jdk-7u60-linux-x64.rpm ->安装jdk 2.Tomcat 安装篇 在apache官方下载tomcat wget http://apache.fayea.com/apache-mirror/tomcat/tomcat-7/v7.0.5

Java 将自定义的对象作为HashMap的key

需要继承Map的equals函数和hashCode函数 package com.category; import java.util.HashMap; public class GenCategoryLevelData { private static HashMap<Category, Integer> categoryLevel = new HashMap<Category, Integer>(); /** * @param args */ public static void

再学Java 之 Integer 包装类缓存

前言:本博文将涉及的Java的自动装箱和自动拆箱,可以参考 这篇文章 和 官方教程 ,这里不再赘述. 首先,先看一个小程序: public class Main { public static void main(String[] args){ Integer i1 = new Integer(1); Integer i2 = new Integer(1); System.out.println(i1 == i2); Integer i3 = 1; Integer i4 = 1; System.

利用java的代理建立缓存

背景: 为了实现组件的复用,几乎所有的项目都会调用一个通用的用户组件(org).各系统和org之间是使用webservice技术进行通,主要是org提供了webservice业务接口.经过了一段时间的使用发现组件相当稳定,正常情况下几乎可以满足所有系统的要求.只是有一个问题比较突出就是当一个方法包含过多的webservice请求时还是会有性能问题,这个问题应该说是webservice的通病.所以这里提供一种解决方法,建立缓存机制. 分析: 首先建立缓存位置其实有两个选择,一是建立在org服务器端

java Annotation 自定义实例

Defining annotations Here is the definition of the annotation above. You can see that annotation definitions look a lot like interface definitions. In fact, they compile to class files like any other Java interface: -------------------------------首先定