
一、介绍
ConcurrentHashMap 是 Java 中一个非常重要的集合类,属于 java.util.concurrent 包。它是一个线程安全的哈希表,允许多个线程同时读写而不会出现数据不一致的问题。ConcurrentHashMap 是 Java 5 引入的,旨在提高并发性能。
特点
-
线程安全:ConcurrentHashMap 采用了分段锁的机制(在 Java 8 之前)或者采用了更细粒度的锁(在 Java 8 之后),允许多个线程并发访问而不会互相阻塞。 -
高性能:由于其设计,ConcurrentHashMap 在并发情况下的性能比传统的 Hashtable 或者 Collections.synchronizedMap(new HashMap<>()) 更好。 -
不支持 null 键和 null 值:与 HashMap 不同,ConcurrentHashMap 不允许使用 null 作为键或值。 -
部分操作是原子性的:例如,putIfAbsent, remove, 和 replace 等方法是原子操作。 -
支持并发读:在没有写操作的情况下,多个线程可以并发地读取数据。
主要方法
以下是一些常用的方法:
put(K key, V value):将指定的值与指定的键关联。get(Object key):返回指定键所映射的值。remove(Object key):如果存在,则移除指定的键及其对应的值。putIfAbsent(K key, V value):如果指定的键尚未映射到值,则将其插入。replace(K key, V oldValue, V newValue):仅在当前映射到指定键的值与指定值相等时,才将其替换为新值。- size(): 返回映射中键-值对的数量。
总结
ConcurrentHashMap 是一个强大的工具,适用于需要高并发读写的场景。它不仅提供了线程安全的操作,还能在高并发环境下保持良好的性能。使用时需要注意的几点包括不支持 null 键和值,以及在某些情况下需要使用特定的原子操作方法。
二、代码
RemainingNumberOfPasswordsCache
package com.hero.lte.ems.security.cache;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RemainingNumberOfPasswordsCache {
private static RemainingNumberOfPasswordsCache instance = new RemainingNumberOfPasswordsCache();
private final Map<String, Integer> map = new ConcurrentHashMap<String, Integer>();
private RemainingNumberOfPasswordsCache() {}
public static RemainingNumberOfPasswordsCache getInstance()
{
return instance;
}
public Integer getRemainingNumberOfPasswords(String accountName)
{
return map.get(accountName);
}
public Map<String, Integer> getRemainingNumberOfPasswords() {
return map;
}
public void addRemainingNumberOfPasswords(String accountName, Integer remainingInputTimes) {
map.put(accountName, remainingInputTimes);
}
public void clearRemainingNumberOfPasswords() {
map.clear();
}
}
使用
RemainingNumberOfPasswordsCache cache = RemainingNumberOfPasswordsCache.getInstance();
cache.addRemainingNumberOfPasswords(account.getUsername(), maxFail - count);
RemainingNumberOfPasswordsCache cache = RemainingNumberOfPasswordsCache.getInstance();
Integer remainingNumberOfPasswords = cache.getRemainingNumberOfPasswords(loginData.get("accountName"));

893

被折叠的 条评论
为什么被折叠?



