Java中的ConcurrentMap接口
ConcurrentMap是一个接口,它是Java Collections Framework 的成员,它在 JDK 1.5 中引入,表示能够处理对它的并发访问而不影响映射中条目的一致性的 Map。 Java.util.concurrent包中存在 ConcurrentMap 接口。除了从 SuperInterface 继承的方法(即Java.util.Map)之外,它还提供了一些额外的方法。它继承了嵌套接口 Map.Entry
HashMap 操作不同步,而 Hashtable 提供同步。虽然 Hashtable 是线程安全的,但它的效率不是很高。为了解决这个问题, Java Collections Framework 在Java 1.5 中引入了ConcurrentMap 。
ConcurrentMap 的层次结构
宣言:
public interface ConcurrentMap extends Map
这里, K是 key Object 的类型, V是 value Object 的类型。
- 它扩展了Java中的 Map 接口。
- ConcurrentNavigableMap
是子接口。 - ConcurrentMap 由 ConcurrentHashMap、 ConcurrentSkipListMap类实现。
- ConcurrentMap 被称为同步 Map。
实现类
由于它属于Java.util.concurrent包,我们必须 import is using
import java.util.concurrent.ConcurrentMap
or
import java.util.concurrent.*
ConcurrentMap 有两个实现类,它们是ConcurrentSkipListMap和ConcurrentHashMap 。 ConcurrentSkipListMap 是 ConcurrentNavigableMap 接口的可扩展实现,它扩展了 ConcurrentMap 接口。 ConcurrentSkipListMap 中的键按自然顺序或在构造对象时使用 Comparator 排序。 ConcurrentSkipListMap 的插入、删除和搜索操作的预期时间成本为log(n) 。它是一个线程安全的类,因此,所有的基本操作都可以同时完成。
句法:
// ConcurrentMap implementation by ConcurrentHashMap
CocurrentMap numbers = new ConcurrentHashMap();
// ConcurrentMap implementation by ConcurrentSkipListMap
ConcurrentMap< ? , ? > objectName = new ConcurrentSkipListMap< ? , ? >();
例子:
Java
// Java Program to illustrate methods
// of ConcurrentMap interface
import java.util.concurrent.*;
class ConcurrentMapDemo {
public static void main(String[] args)
{
// Since ConcurrentMap is an interface,
// we create instance using ConcurrentHashMap
ConcurrentMap m = new ConcurrentHashMap();
m.put(100, "Geeks");
m.put(101, "For");
m.put(102, "Geeks");
// Here we cant add Hello because 101 key
// is already present
m.putIfAbsent(101, "Hello");
// We can remove entry because 101 key
// is associated with For value
m.remove(101, "For");
// Now we can add Hello
m.putIfAbsent(101, "Hello");
// We can replace Hello with For
m.replace(101, "Hello", "For");
System.out.println("Map contents : " + m);
}
}
Java
// Java Program to demonstrate adding
// elements
import java.util.concurrent.*;
class AddingElementsExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap mpp = new ConcurrentSkipListMap();
// Adding elements to this map
// using put() method
for (int i = 1; i <= 5; i++)
mpp.put(i, i);
// Print map to the console
System.out.println("After put(): " + mpp);
}
}
Java
// Java Program to demonstrate removing
// elements
import java.util.concurrent.*;
class RemovingElementsExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap mpp = new ConcurrentSkipListMap();
// Adding elements to this map
// using put method
for (int i = 1; i <= 5; i++)
mpp.put(i, i);
// remove() mapping associated
// with key 1
mpp.remove(1);
System.out.println("After remove(): " + mpp);
}
}
Java
// Java Program to demonstrate accessing
// elements
import java.util.concurrent.*;
class AccessingElementsExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap chm = new ConcurrentSkipListMap();
// insert mappings using put method
chm.put(100, "Geeks");
chm.put(101, "for");
chm.put(102, "Geeks");
chm.put(103, "Contribute");
// Displaying the HashMap
System.out.println("The Mappings are: ");
System.out.println(chm);
// Display the value of 100
System.out.println("The Value associated to "
+ "100 is : " + chm.get(100));
// Getting the value of 103
System.out.println("The Value associated to "
+ "103 is : " + chm.get(103));
}
}
Java
import java.util.concurrent.*;
import java.util.*;
public class TraversingExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap chmap = new ConcurrentSkipListMap();
// Add elements using put()
chmap.put(8, "Third");
chmap.put(6, "Second");
chmap.put(3, "First");
chmap.put(11, "Fourth");
// Create an Iterator over the
// ConcurrentSkipListMap
Iterator > itr
= chmap.entrySet().iterator();
// The hasNext() method is used to check if there is
// a next element The next() method is used to
// retrieve the next element
while (itr.hasNext()) {
ConcurrentSkipListMap
.Entry entry
= itr.next();
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
}
Map contents : {100=Geeks, 101=For, 102=Geeks}
基本方法
1.添加元素
ConcurrentSkipListMap 的 put() 方法是Java中的一个内置函数,它将指定的值与此映射中的指定键相关联。如果映射先前包含键的映射,则替换旧值。
Java
// Java Program to demonstrate adding
// elements
import java.util.concurrent.*;
class AddingElementsExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap mpp = new ConcurrentSkipListMap();
// Adding elements to this map
// using put() method
for (int i = 1; i <= 5; i++)
mpp.put(i, i);
// Print map to the console
System.out.println("After put(): " + mpp);
}
}
After put(): {1=1, 2=2, 3=3, 4=4, 5=5}
2.删除元素
ConcurrentSkipListMap 的 remove() 方法是Java中的一个内置函数,用于从该映射中删除指定键的映射。如果该特定键没有映射,则该方法返回 null。执行此方法后,地图的大小会减小。
Java
// Java Program to demonstrate removing
// elements
import java.util.concurrent.*;
class RemovingElementsExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap mpp = new ConcurrentSkipListMap();
// Adding elements to this map
// using put method
for (int i = 1; i <= 5; i++)
mpp.put(i, i);
// remove() mapping associated
// with key 1
mpp.remove(1);
System.out.println("After remove(): " + mpp);
}
}
After remove(): {2=2, 3=3, 4=4, 5=5}
3. 访问元素
我们可以使用 get() 方法访问 ConcurrentSkipListMap 的元素,下面给出了这个示例。
Java
// Java Program to demonstrate accessing
// elements
import java.util.concurrent.*;
class AccessingElementsExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap chm = new ConcurrentSkipListMap();
// insert mappings using put method
chm.put(100, "Geeks");
chm.put(101, "for");
chm.put(102, "Geeks");
chm.put(103, "Contribute");
// Displaying the HashMap
System.out.println("The Mappings are: ");
System.out.println(chm);
// Display the value of 100
System.out.println("The Value associated to "
+ "100 is : " + chm.get(100));
// Getting the value of 103
System.out.println("The Value associated to "
+ "103 is : " + chm.get(103));
}
}
The Mappings are:
{100=Geeks, 101=for, 102=Geeks, 103=Contribute}
The Value associated to 100 is : Geeks
The Value associated to 103 is : Contribute
4. 遍历
我们可以使用 Iterator 接口来遍历 Collection Framework 的任何结构。由于迭代器使用一种类型的数据,我们使用 Entry< ? , ? > 将两种不同的类型解析为兼容的格式。然后使用 next() 方法我们打印 ConcurrentSkipListMap 的元素。
Java
import java.util.concurrent.*;
import java.util.*;
public class TraversingExample {
public static void main(String[] args)
{
// Instantiate an object
// Since ConcurrentMap
// is an interface so We use
// ConcurrentSkipListMap
ConcurrentMap chmap = new ConcurrentSkipListMap();
// Add elements using put()
chmap.put(8, "Third");
chmap.put(6, "Second");
chmap.put(3, "First");
chmap.put(11, "Fourth");
// Create an Iterator over the
// ConcurrentSkipListMap
Iterator > itr
= chmap.entrySet().iterator();
// The hasNext() method is used to check if there is
// a next element The next() method is used to
// retrieve the next element
while (itr.hasNext()) {
ConcurrentSkipListMap
.Entry entry
= itr.next();
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
}
Key = 3, Value = First
Key = 6, Value = Second
Key = 8, Value = Third
Key = 11, Value = Fourth
ConcurrentMap 的方法
- K - 映射中键的类型。
- V – 映射中映射的值的类型。
METHOD | DESCRIPTION |
---|---|
compute(K key, BiFunction super K,? super V,? extends V> remappingFunction) | Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
computeIfAbsent(K key, Function super K,? extends V> mappingFunction) | If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null. |
computeIfPresent(K key, BiFunction super K,? super V,? extends V> remappingFunction) | If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value. |
forEach(BiConsumer super K,? super V> action) | Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. |
getOrDefault(Object key, V defaultValue) | Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. |
merge(K key, V value, BiFunction super V,? super V,? extends V> remappingFunction) | If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
putIfAbsent(K key, V value) | If the specified key is not already associated with a value, associates it with the given value. |
remove(Object key, Object value) | Removes the entry for a key only if currently mapped to a given value. |
replace(K key, V value) | Replaces the entry for a key only if currently mapped to some value. |
replace(K key, V oldValue, V newValue) | Replaces the entry for a key only if currently mapped to a given value. |
replaceAll(BiFunction super K,? super V,? extends V> function) | Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
从接口Java .util.Map 继承的方法
METHOD | DESCRIPTION |
---|---|
clear() | Removes all of the mappings from this map (optional operation). |
containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
containsValue(Object value) | Returns true if this map maps one or more keys to the specified value. |
entry(K k, V v) | Returns an immutable Map.Entry containing the given key and value. |
entrySet() | Returns a Set view of the mappings contained in this map. |
equals(Object o) | Compares the specified object with this map for equality. |
get(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
hashCode() | Returns the hash code value for this map. |
isEmpty() | Returns true if this map contains no key-value mappings. |
keySet() | Returns a Set view of the keys contained in this map. |
of() | Returns an immutable map containing zero mappings. |
of(K k1, V v1) | Returns an immutable map containing a single mapping. |
of(K k1, V v1, K k2, V v2) | Returns an immutable map containing two mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3) | Returns an immutable map containing three mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) | Returns an immutable map containing four mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) | Returns an immutable map containing five mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) | Returns an immutable map containing six mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) | Returns an immutable map containing seven mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) | Returns an immutable map containing eight mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) | Returns an immutable map containing nine mappings. |
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) | Returns an immutable map containing ten mappings. |
ofEntries(Map.Entry extends K,? extends V>… entries) | Returns an immutable map containing keys and values extracted from the given entries. |
put(K key, V value) | Associates the specified value with the specified key in this map (optional operation). |
putAll(Map extends K,? extends V> m) | Copies all of the mappings from the specified map to this map (optional operation). |
remove(Object key) | Removes the mapping for a key from this map if it is present (optional operation). |
size() | Returns the number of key-value mappings in this map. |
values() | Returns a Collection view of the values contained in this map. |
参考: Java : Java