• 本地缓存设计


    被问到本地缓存设计,有点蒙,事后反应过来,何必一个Map呢,两个就可以解决了。真是当时脑子短路了。

    package cache;

    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;

    public class MyCache<K, V> {

    private static class ValueObject<T> {

    private T value;
    private long timeout;

    private ValueObject(T value, long timeout) {
    super();
    this.value = value;
    this.timeout = timeout;
    }

    private T getValue() {
    return value;
    }

    private long getTimeout() {
    return timeout;
    }

    }

    public static final Map<Object, ValueObject> localCache = new ConcurrentHashMap<Object, ValueObject>();

    public static Object set(Object key, ValueObject value, long timeout) {
    long currentTime = System.currentTimeMillis();
    ValueObject valueObject = localCache.get(key);
    if (localCache.keySet().contains(key)
    && (valueObject.getTimeout() == 0 || currentTime <= valueObject.getTimeout())) {
    return valueObject.getValue();
    } else {
    ValueObject oldValueObject = localCache.put(key, new ValueObject(value, currentTime + timeout));
    return oldValueObject == null ? null : oldValueObject.getValue();
    }
    }

    public static <T> T set(Object key, ValueObject value) {
    ValueObject oldValueObject = localCache.put(key, new ValueObject(value, 0));
    return (T) (oldValueObject == null ? null : oldValueObject.getValue());
    }

    public static <T> T get(Object key) {
    long currentTime = System.currentTimeMillis();
    ValueObject valueObject = localCache.get(key);
    if (valueObject == null) {
    return null;
    }
    if (valueObject.getTimeout() == 0 || currentTime <= valueObject.getTimeout()) {
    return (T) valueObject.getValue();
    } else {
    localCache.remove(key);
    return null;
    }
    }

    }

    思路清晰了,就好写了,借鉴了下别人的思路,有错误欢迎指出。

  • 相关阅读:
    函数
    文件的基本操作
    c语言程序设计案例教程(第2版)笔记(一)—零散、输入输出、最小公倍数、选择排序、冒泡排序
    c语言中的rand()函数用法
    c语言 error C4996: 'strupr': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
    Python之列表生成式、生成器
    Python之迭代器
    Python之装饰器
    Linux之线程相关命令及常用命令
    重写、重构、重载区别
  • 原文地址:https://www.cnblogs.com/anyehome/p/8858848.html
Copyright © 2020-2023  润新知