码迷,mamicode.com
首页 > 编程语言 > 详细

50行代码实现缓存,JAVA内存模型原理

时间:2017-04-07 12:36:02      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:new   city   return   current   内存   style   pac   simple   ash   

遇见这样的高人怎么办??下面是一个简单缓存的实现,相当牛叉!自己看吧,只有50行代码。

摘自:http://www.oschina.net/code/snippet_55577_3887

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public final class SimpleCache<K,V> {
 
    private final Lock lock = new ReentrantLock();
    private final int maxCapacity;
    private final Map<K,V> eden;
    private final Map<K,V> perm;
 
    public SimpleCache(int maxCapacity) {
        this.maxCapacity = maxCapacity;
        this.eden = new ConcurrentHashMap<K,V>(maxCapacity);
        this.perm= new WeakHashMap<K,V>(maxCapacity);
    }
 
    public V get(K k) {
        V v = this.eden.get(k);
        if (v == null) {
            lock.lock();
            try{
                v = this.perm.get(k);
            }finally{
                lock.unlock();
            }
            if (v != null) {
                this.eden.put(k, v);
            }
        }
        return v;
    }
 
    public void put(K k, V v) {
        if (this.eden.size() >= maxCapacity) {
            lock.lock();
            try{
                this.perm.putAll(this.eden);
            }finally{
                lock.unlock();
            }
            this.eden.clear();
        }
    this.eden.put(k, v);
    }
}

 

50行代码实现缓存,JAVA内存模型原理

标签:new   city   return   current   内存   style   pac   simple   ash   

原文地址:http://www.cnblogs.com/henuyuxiang/p/6677515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!