java 緩衝 ConcurrentHashMap 單例 簡單樣本

來源:互聯網
上載者:User

1、實現代碼

import java.util.HashMap;import java.util.concurrent.ConcurrentHashMap;public class LocalCache {    private LocalCache() {    }   // 防止在外部執行個體化    // 使用volatile延遲初始化,防止編譯器重排序    private static volatile LocalCache instance;    public static LocalCache getInstance() {        // 對象執行個體化時與否判斷(不使用同步代碼塊,instance不等於null時,直接返回對象,提高運行效率)        if (instance == null) {            // 同步代碼塊(對象未初始化時,使用同步代碼塊,保證多線程訪問時對象在第一次建立後,不再重複被建立)            synchronized (LocalCache.class) {                // 未初始化,則初始instance變數                if (instance == null) {                    instance = new LocalCache();                }            }        }        return instance;    }    protected static final ConcurrentHashMap<String, Object> dataMap = new ConcurrentHashMap<String, Object>();    private static final Object lock = new Object();    public static Object get(String key) {        Object v = dataMap.get(key);        if (v == null) {            synchronized (lock) {                v = dataMap.get(key);     // Check again to avoid re-load            }        }        return v;    }    public static synchronized void set(String key, Object value) {        dataMap.put(key, value);    }    public static synchronized boolean isAccess(String ip, long maxTimeInterval, long maxTimes) {        @SuppressWarnings("unchecked")        HashMap<String, Object> map = (HashMap<String, Object>) dataMap.get(ip);        if (null == map) {            map = new HashMap<String, Object>();            map.put("times", 1);            map.put("timestamp", System.currentTimeMillis());            LocalCache.set(ip, map);            System.err.println(ip+":"+map);            return true;        } else {            int times = (int) map.get("times");            long timestamp = (long) map.get("timestamp");            if (System.currentTimeMillis() - timestamp > maxTimeInterval*1000) {                map.put("times", 1);                map.put("timestamp", System.currentTimeMillis());                LocalCache.set(ip, map);                System.err.println(ip+":"+map);                return true;            } else {                if (times < maxTimes) {                    map.put("times", times + 1);                    LocalCache.set(ip, map);                    System.err.println(ip+":"+map);                    return true;                } else {                    System.err.println("false");                    return false;                }            }        }    }}

2、測試代碼

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import com.seed.file.util.cache.LocalCache;public class LocalCacheTest implements Runnable {    @Override    public void run() {        LocalCache.isAccess("127.0.0.1", 3000L, 3);    }    public static void main(String[] args) {        ExecutorService pool = Executors.newCachedThreadPool();        LocalCacheTest test = new LocalCacheTest();        for (int i = 0; i < 100; i++) {            pool.execute(test);        }    }}

3、測試結果

127.0.0.1:{times=1, timestamp=1496801373728}
127.0.0.1:{times=2, timestamp=1496801373728}
127.0.0.1:{times=3, timestamp=1496801373728}
false
false
false
false
false
false
false

...

聯繫我們

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