如何使用JDK来实现自己的缓存(支持高并发)?

需求分析

项目中经常会遇到这种场景:一份数据需要在多处共享,有些数据还有时效性,过期自动失效。比如手机验证码,发送之后需要缓存起来,然后处于安全性考虑,一般还要设置有效期,到期自动失效。我们怎么实现这样的功能呢?

解决方案

使用现有的缓存技术框架,比如redis,ehcache。优点:成熟,稳定,功能强大;缺点,项目需要引入对应的框架,不够轻量。

如果不考虑分布式,只是在单线程或者多线程间作数据缓存,其实完全可以自己手写一个缓存工具。下面就来简单实现一个这样的工具。

代码实现

package com.homedo.microservice.bff.scc.scp.compositeservice.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @description:
 * @author: jiangchongwen
 * @createTime: 2021-11-02 09:27
 */
public class MemoryCache {
    //键值对集合
    private final static Map<String, Entity> map = new HashMap<>();
    //定时器线程池,用于清除过期缓存
    private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 添加缓存
     *
     * @param key  键
     * @param data 值
     */
    public synchronized static void put(String key, Object data) {
        MemoryCache.put(key, data, 0);
    }

    /**
     * 添加缓存
     *
     * @param key    键
     * @param data   值
     * @param expire 过期时间,单位:毫秒, 0表示无限长
     */
    public synchronized static void put(String key, Object data, long expire) {
        //清除原键值对
        MemoryCache.remove(key);
        //设置过期时间
        if (expire > 0) {
            Future future = executor.schedule(new Runnable() {
                @Override
                public void run() {
                    //过期后清除该键值对
                    synchronized (MemoryCache.class) {
                        map.remove(key);
                    }
                }
            }, expire, TimeUnit.MILLISECONDS);
            map.put(key, new Entity(data, future));
        } else {
            //不设置过期时间
            map.put(key, new Entity(data, null));
        }
    }

    /**
     * 读取缓存
     *
     * @param key 键
     * @return
     */
    public synchronized static Object get(String key) {
        Entity entity = map.get(key);
        return entity == null ? null : entity.getValue();
    }

    /**
     * 读取缓存
     *
     * @param key   键
     * @param clazz 值类型
     * @return
     */
    public synchronized static <T> T get(String key, Class<T> clazz) {
        return clazz.cast(MemoryCache.get(key));
    }

    /**
     * 清除缓存
     *
     * @param key
     * @return
     */
    public synchronized static Object remove(String key) {
        //清除原缓存数据
        Entity entity = map.remove(key);
        if (entity == null) {
            return null;
        }
        //清除原键值对定时器
        Future future = entity.getFuture();
        if (future != null) {
            future.cancel(true);
        }
        return entity.getValue();
    }

    /**
     * 查询当前缓存的键值对数量
     *
     * @return
     */
    public synchronized static int size() {
        return map.size();
    }

    /**
     * 缓存实体类
     */
    private static class Entity {
        //键值对的value
        private Object value;
        //定时器Future
        private Future future;

        public Entity(Object value, Future future) {
            this.value = value;
            this.future = future;
        }

        /**
         * 获取值
         *
         * @return
         */
        public Object getValue() {
            return value;
        }

        /**
         * 获取Future对象
         *
         * @return
         */
        public Future getFuture() {
            return future;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String key = "id";
        //不设置过期时间
        System.out.println("***********不设置过期时间**********");
        MemoryCache.put(key, 123);
        System.out.println("key:" + key + ", value:" + MemoryCache.get(key));
        System.out.println("key:" + key + ", value:" + MemoryCache.remove(key));
        System.out.println("key:" + key + ", value:" + MemoryCache.get(key));

        //设置过期时间
        System.out.println("\n***********设置过期时间**********");
        MemoryCache.put(key, "123456", 1000);
        System.out.println("key:" + key + ", value:" + MemoryCache.get(key));
        TimeUnit.MILLISECONDS.sleep(1500);
        System.out.println("key:" + key + ", value:" + MemoryCache.get(key));

        /******************并发性能测试************/
        System.out.println("\n***********并发性能测试************");
        //创建有10个线程的线程池,将1000000次操作分10次添加到线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Future[] futures = new Future[10];
        /********添加********/
        {
            long start = System.currentTimeMillis();
            for (int j = 0; j < 10; j++) {
                futures[j] = executorService.submit(() -> {
                    for (int i = 0; i < 100000; i++) {
                        MemoryCache.put(Thread.currentThread().getId() + key + i, i, 300000);
                    }
                });
            }
            //等待全部线程执行完成,打印执行时间
            for (Future future : futures) {
                future.get();
            }
            System.out.printf("添加耗时:%dms\n", System.currentTimeMillis() - start);
        }

        /********查询********/
        {
            long start = System.currentTimeMillis();
            for (int j = 0; j < 10; j++) {
                futures[j] = executorService.submit(() -> {
                    for (int i = 0; i < 100000; i++) {
                        Object obj = MemoryCache.get(Thread.currentThread().getId() + key + i);
                        System.out.println("cacheObj:"+ obj);
                    }
                });
            }
            //等待全部线程执行完成,打印执行时间
            for (Future future : futures) {
                future.get();
            }
            System.out.printf("查询耗时:%dms\n", System.currentTimeMillis() - start);
        }

        System.out.println("当前缓存容量:" + MemoryCache.size());
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDK7中,Class.forName方法在高并发环境下可能存在线程安全问题。具体表现为多线程同时调用Class.forName方法时,可能会出现重复加载类的情况,导致类的静态代码块被重复执行。这种情况会导致程序出现各种异常,例如类初始化异常、单例被重复创建等。 这个问题的原因在于JDK7中的Class对象缓存机制存在缺陷,当多个线程同时调用Class.forName方法时,可能会导致多个线程同时从缓存中获取到同一个Class对象,从而导致类的静态代码块被重复执行。 以下是一个伪代码示例,用于复现这种情况: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestClassForName { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) { executorService.submit(() -> { try { Class.forName("TestClass"); } catch (ClassNotFoundException e) { e.printStackTrace(); } }); } executorService.shutdown(); } static class TestClass { static { System.out.println(Thread.currentThread().getName() + " init TestClass"); } } } ``` 在这个示例中,我们创建了一个线程池,同时提交了100个任务,每个任务都会调用Class.forName方法加载TestClass类。TestClass类中有一个静态代码块,用于输出当前线程的名称和初始化TestClass类的信息。 运行这段代码,可能会出现以下输出结果: ``` pool-1-thread-1 init TestClass pool-1-thread-2 init TestClass pool-1-thread-3 init TestClass pool-1-thread-4 init TestClass pool-1-thread-5 init TestClass pool-1-thread-6 init TestClass pool-1-thread-7 init TestClass pool-1-thread-7 init TestClass pool-1-thread-8 init TestClass pool-1-thread-9 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass pool-1-thread-10 init TestClass ``` 可以看到,在高并发环境下,TestClass类的静态代码块被重复执行了多次,导致输出了重复的信息。 为了解决这个问题,可以使用类加载器来加载类,而不是直接调用Class.forName方法。另外,JDK8及以上版本已经修复了这个问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值