分享一個java Map實現的cache manager,定時清除緩衝起來的值,mapmanager

來源:互聯網
上載者:User

分享一個java Map實現的cache manager,定時清除緩衝起來的值,mapmanager

原文:分享一個java Map實現的cache manager,定時清除緩衝起來的值

原始碼:http://www.zuidaima.com/share/1550463676140544.htm

用來儲存短暫對象的緩衝類,實現Map介面,內部有一個定時器用來清除到期(30秒)的對象。 為避免建立過多線程,沒有特殊要求請使用getDefault()方法來擷取本類的執行個體。

package com.zuidaima.modules.common.util;import java.util.AbstractMap;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;/** * 用來儲存短暫對象的緩衝類,實現Map介面,內部有一個定時器用來清除到期(30秒)的對象。 * 為避免建立過多線程,沒有特殊要求請使用getDefault()方法來擷取本類的執行個體。 * @author www.zuidaima.com * @param <K> * @param <V> */public class CacheMap<K, V> extends AbstractMap<K, V> {private static final long DEFAULT_TIMEOUT = 30000;private static CacheMap<Object, Object> defaultInstance;public static synchronized final CacheMap<Object, Object> getDefault() {if (defaultInstance == null) {defaultInstance = new CacheMap<Object, Object>(DEFAULT_TIMEOUT);}return defaultInstance;}private class CacheEntry implements Entry<K, V> {long time;V value;K key;CacheEntry(K key, V value) {super();this.value = value;this.key = key;this.time = System.currentTimeMillis();}@Overridepublic K getKey() {return key;}@Overridepublic V getValue() {return value;}@Overridepublic V setValue(V value) {return this.value = value;}}private class ClearThread extends Thread {ClearThread() {setName("clear cache thread");}public void run() {while (true) {try {long now = System.currentTimeMillis();Object[] keys = map.keySet().toArray();for (Object key : keys) {CacheEntry entry = map.get(key);if (now - entry.time >= cacheTimeout) {synchronized (map) {map.remove(key);}}}Thread.sleep(cacheTimeout);} catch (Exception e) {e.printStackTrace();}}}}private long cacheTimeout;private Map<K, CacheEntry> map = new HashMap<K, CacheEntry>();public CacheMap(long timeout) {this.cacheTimeout = timeout;new ClearThread().start();}@Overridepublic Set<Entry<K, V>> entrySet() {Set<Entry<K, V>> entrySet = new HashSet<Map.Entry<K, V>>();Set<Entry<K, CacheEntry>> wrapEntrySet = map.entrySet();for (Entry<K, CacheEntry> entry : wrapEntrySet) {entrySet.add(entry.getValue());}return entrySet;}@Overridepublic V get(Object key) {CacheEntry entry = map.get(key);return entry == null ? null : entry.value;}@Overridepublic V put(K key, V value) {CacheEntry entry = new CacheEntry(key, value);synchronized (map) {map.put(key, entry);}return value;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.