Java進程內緩衝

來源:互聯網
上載者:User

標籤:with   訪問   start   thread   art   時間戳記   緩衝   return   避免   

今天和同事聊到了緩衝,在Java中實現進程緩衝。這裡主要思想是,用一個map做緩衝。緩衝有個存留時間,到期就刪除緩衝。這裡可以考慮兩種刪除策略,一種是起一個線程,定期刪除到期的key。第二個是,剔除模式,比較懶,訪問到某個key的時候才,才去檢查這個key是否到期,到期刪除。

首先,對要緩衝的value做了層封裝,帶了個時間戳記

/** * Created by gxf on 2017/6/28. */public class ValueWithTimeStamp<V>{    private long expireTime;    private V value;    public ValueWithTimeStamp(long expireTime, V value) {        this.expireTime = expireTime;        this.value = value;    }    public long getExpireTime() {        return expireTime;    }    public void setExpireTime(long expireTime) {        this.expireTime = expireTime;    }    public V getValue() {        return value;    }    public void setValue(V value) {        this.value = value;    }}

ok,起線程定期刪除策略的模式

import java.util.Map;import java.util.concurrent.ConcurrentHashMap;/** * Created by gxf on 2017/6/28. * 使用線程,定期刪除到期的key */public class CacheMap<K, V>  {    //這裡使用ConcurrentHashMap避免,clean的時候,主線程修改chache,造成異常,    //使用ConcurrentHashMap可以控制並發修改cache    private Map<K, ValueWithTimeStamp<V>> cache = new ConcurrentHashMap<K, ValueWithTimeStamp<V>>();    private static boolean cleanTaskIsRunning = false;    //ttl 到期時間 單位:秒    public void put(K key, V value, int ttl){        long expireTime = System.currentTimeMillis() + ttl * 1000;        ValueWithTimeStamp<V> valueWithTimeStamp = new ValueWithTimeStamp<>(expireTime, value);        cache.put(key, valueWithTimeStamp);        if(!cleanTaskIsRunning){            startCleanTask();            cleanTaskIsRunning = !cleanTaskIsRunning;        }    }    public V get(K key){        ValueWithTimeStamp<V> valueWithTimeStamp = cache.get(key);        return null == valueWithTimeStamp ? null : valueWithTimeStamp.getValue();    }    /**     * 啟動清理線程     * */    private void startCleanTask(){        Thread cleanThread = new Thread(new CleanTask());        cleanThread.start();    }    /**     * 清理到期的key     * */    class CleanTask implements Runnable{        public void run(){            while(true){                long currentTime =  System.currentTimeMillis();                //遍曆map                for(Map.Entry<K, ValueWithTimeStamp<V>> entry : cache.entrySet()){                    ValueWithTimeStamp<V> valueWithTimeStamp = entry.getValue();                    long expireTime = valueWithTimeStamp.getExpireTime();                    //到期時間到了                    if(currentTime > expireTime){                        System.out.println("key : " + entry.getKey() + " expired ");                        cache.remove(entry.getKey());                    } //if                } //for                //每隔1s掃描map對象                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            } //while        }    }}

注意,這裡需要使用ConcurrentHashMap做緩衝。不然會出現多線線程操作map對象的異常

第二種策略,剔除模式

import java.util.Map;import java.util.concurrent.ConcurrentHashMap;/** * Created by 58 on 2017/6/28. * 這裡使用懶惰模式,擷取key的時候,才剔除到期的key */public class CacheMap1<K, V> {    private Map<K, ValueWithTimeStamp<V>> cache = new ConcurrentHashMap<K, ValueWithTimeStamp<V>>();    public void put(K key, V value, int ttl){        long expireTime = System.currentTimeMillis() + ttl * 1000;        ValueWithTimeStamp<V> valueWithTimeStamp = new ValueWithTimeStamp<V>(expireTime, value);        cache.put(key, valueWithTimeStamp);    }    public V get(K key){        ValueWithTimeStamp<V> valueWithTimeStamp = cache.get(key);        long expireTime = valueWithTimeStamp.getExpireTime();        long currentTime = System.currentTimeMillis();        //key已經到期,刪除,返回null        if(currentTime > expireTime){            System.out.println("key :" + key + " is expired.");            cache.remove(key);            return null;        }        return cache.get(key).getValue();    }}

項目中用到了redis,用這種方式應該會更快,這兩天最佳化一下代碼

Java進程內緩衝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.