In layman's Java Concurrency (16): Concurrent Container Part 1 Concurrentmap (1) [Go]

Source: Internet
Author: User

Starting with this section formally enters the part of the concurrent container and looks at what concurrent containers the JDK 6 brings.

Under JDK 1.4 only vectors and hashtable are thread-safe collections (also known as concurrent containers, the collections.synchronized* series can also be seen as thread-safe implementations). Starting with JDK 5 added thread-Safe map interface Concurrentmap and thread-safe queue Blockingqueue (although queue is also a new collection introduced in the same period, but the specification does not stipulate that it must be thread-safe, in fact some implementations are not thread-safe, such as Priorityqueue, Arraydeque, LinkedList, and so on, in the queue section will be discussed in detail the structure of these queues and implementation).

Review the architecture of map before you introduce Concurrencymap. Describes the architecture of the map, where the blue font is the new concurrency container after JDK 5.

The following points are explained:

    1. Hashtable is a built-in implementation of the map's only thread-safe prior to JDK 5 (Collections.synchronizedmap does not count). In particular, Hashtable's T is lowercase (not knowing why), Hashtable inherits Dictionary (Hashtable is its only exposed subclass) and does not inherit Abstractmap or HashMap. Although the structure of Hashtable and HashMap is very similar, there is not much connection between them.
    2. Concurrenthashmap is a thread-safe version of HashMap, and Concurrentskiplistmap is a thread-safe version of TreeMap.
    3. The final available thread-safe version of the map implementation is concurrenthashmap/concurrentskiplistmap/hashtable/properties four, but Hashtable is a obsolete class library, Therefore, if possible, concurrenthashmap and concurrentskiplistmap should be used.

Back to the point, this section focuses on Concurrenthashmap APIs and applications, and the next section begins with the rationale and analysis.

In addition to the method of implementing the object in the map interface, Concurrenthashmap also implements the four methods within the Concurrentmap.

V putifabsent (K key,v value)

If there is no value corresponding to the key, add value to the map with key, otherwise return the old value corresponding to the key. This is equivalent to the operation in Listing 1:

Listing 1 equivalent operations for Putifabsent

if (!map.containskey (key))
Return Map.put (key, value);
Else
return Map.get (key);

As mentioned in the previous chapters, a sequence of two or more atomic operations is not necessarily an atomic operation. For example, the above operation is not an atomic operation even in Hashtable. And Putifabsent is a thread-safe version of the operation.

Some people like to use this feature to implement singleton patterns , such as Listing 2.

Implementation of the list of 21 singleton patterns

Package xylz.study.concurrency;

Import Java.util.concurrent.ConcurrentHashMap;
Import Java.util.concurrent.ConcurrentMap;

public class ConcurrentDemo1 {

Private static final concurrentmap<string, concurrentdemo1> map = new concurrenthashmap<string, Concurrentdemo1> ();
private static CONCURRENTDEMO1 instance;
public static ConcurrentDemo1 getinstance () {
if (instance = = null) {

Map.putifabsent ("INSTANCE", New ConcurrentDemo1 ());

Instance = Map.get ("instance");
}
return instance;
}

Private ConcurrentDemo1 () {
}

}

Of course, this is just an example of operation, in fact there are many implementations and comparisons in the singleton pattern article. Listing 2 may be useful in cases where there are a large number of singleton cases, which are rarely used in the case of singleton patterns. However, this approach avoids the possibility of submitting multiple results to the same key in the map, and is sometimes useful for removing duplicate records (if the format of the record is more fixed).

Boolean Remove (Object key,object value)

The entry for the key is removed only if the entry for the key is currently mapped to the given value. This is equivalent to the operation in Listing 3.

Listing 3 equivalent operation of Remove (Object,object)

if (Map.containskey (key) && Map.get (key). Equals (value)) {
Map.Remove (key);
return true;
}
return false;

Because the collection class typically compares the hashcode and Equals methods, and the two methods are inside the object, so if the two objects are consistent with the hashcode, and the Equals method is overridden, then the two objects are "the same" in the collection class, Whether it is the same object or an object of the same type. In other words, as long as Key1.hashcode () ==key2.hashcode () && key1.equals (Key2), then Key1 and Key2 are considered consistent within the collection class, even if their class type is inconsistent. Therefore, in many collection classes, it is possible to compare (or locate) by object type. For example, although the map can only be added by the type of <K,V>, but the deletion is allowed to be manipulated by an object, rather than the type K.

Now that the map has a remove (Object) method, why does Concurrentmap need the Remove (Object,object) method? This is because although the key in the map does not change, but value may have been modified by other threads, if the modified value is what we expect, then we cannot take a key to delete the value, although our expectation is to delete the old value of this key.

This feature is described in the atomicmarkablereference and atomicstampedreference of the Atomic Operations Section.

Boolean replace (K key,v oldvalue,v newvalue)

The entry for the key is replaced only if the entry for the key is currently mapped to the given value. This is equivalent to the operation in Listing 4.

Listing 4 equivalent operations for replace (K,V,V)

if (Map.containskey (key) && Map.get (key). Equals (OldValue)) {
Map.put (key, NewValue);
return true;
}
return false;

V Replace (K key,v value)

Updates the value for this key only when the current key exists. This is equivalent to the operation in Listing 5.

Listing 5 equivalent operations for replace (K,V)

if (Map.containskey (key)) {
Return Map.put (key, value);
}
return null;

Replace (K,V,V) is an increase in the operation of matching oldvalue compared to replace (K,V).

In fact, these 4 extension methods, is the CONCURRENTMAP comes with four operations, in fact, we are more concerned about the operation of map itself. Of course, without these 4 methods, we may need extra locks to complete similar functions, so there is always better than none. For example, listing 6, if there is no putifabsent built-in method, we need to completely lock the entire map if we want to do this, which greatly reduces the concurrency of concurrentmap. This is discussed in detail in the next section.

Listing 6 external implementations of Putifabsent

Public V putifabsent (K key, V value) {
Synchronized (map) {
if (!map.containskey (key)) return Map.put (key, value);
return Map.get (key);
}
}

Resources:

      • Single-instance mode complete parsing
      • Atomic Operation Part 2 array, atomic operation of the reference

In layman's Java Concurrency (16): Concurrent Container Part 1 Concurrentmap (1) [Go]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.