Thread-safe collection
- Overview Java frame set (a) - List Points Interface DETAILED DESCRIPTION
- Java Collections Framework Overview (two) - a set of generic tools and Collections
- Java Collections Framework Overview (three) - HashSet de-duplication principle (HashCode)
- Java Collections Framework Overview (four) - Map collection system and the principle underlying implementation
- A collection of related knowledge Review
- FIG frame set (Map omitted)
- Collection of utility methods
- CopyOnWriteArrayList class
- Learn to read and write locks
- Source code analysis
- CopyOnWriteArrayList exclusive right to read and write?
- how to use?
- vector与CopyOnWriteArrayList
- summary
- CopyOnWriteArraySet class
If your concept related to the set before a certain understanding, that reading of this blog will make you have a broader set of knowledge, if you are a little fuzzy on the concept of a collection, you can take the initiative to point to open the link below We hope to help it to you!
-
Overview Java frame set (a) - List Points Interface DETAILED DESCRIPTION
-
Java Collections Framework Overview (two) - a set of generic tools and Collections
-
Java Collections Framework Overview (three) - HashSet de-duplication principle (HashCode)
-
Java Collections Framework Overview (four) - Map collection system and the principle underlying implementation
A collection of related knowledge Review
The following summary of basic knowledge about the link has a detailed blog at the beginning of the text, can point to open for more reading.
-
ArrayList
array structure to achieve, fast queries, additions and deletions slow
JDK1.2 version. Fast operating efficiency,Thread safe -
LinkedList
list implementation, slow queries, additions and deletions fast -
Vector
array structure to achieve, fast queries, additions and deletions slow
JDK1.0 version. Slow operating efficiency,Thread Safety -
HashSet
This class implements the Set interface, backed by a hash table (actuallyHashMap
instance). Iterative sequence set does not make any guarantee; in particular, it can not guarantee the order remained unchanged for some time. This class allows null elements. (HashSet
Based on theHashCode
implemented elements not duplicate) -
SortedSort
the Set further provides a total ordering its elements. Elements using their natural order, or generally create an orderlySet
provided whenComparator
sorting. Set to change the iterator will traverse ascending order of elements in the collection. It provides several additional operations to take advantage of ordering. (This interface is the set of analoguesSortedMap
). -
LinkedHashSet
hash table and linked list implementation of theSet
interface, with predictable iteration order. This implementation is differentHashSet
, it maintains a doubly linked list running for all entries. ThatLinkedHashSet
may be reserved for our insertion order. -
TreeSet
implement liter descending order, if need to use TreeSet sort must be allowed to compare objects that implementComparable
the interface, and override thecompareTo()
method, the method defined sort criteria (according to what sort), sort (ascending or descending). -
HashMap
based implementation hash table ofMap
the interface. This implementation provides all of the optional map operations, and allowsnull
the value ofnull
the key. (Except that it is not synchronized, and allow null outside theHashMap
class roughly equivalentHashtable
). This class can not be guaranteed sequence mapping; in particular, it does not guarantee that the order constancy.
JDK1.2 version,Thread safe, Fast operating efficiency; allowednull
asKey
orvalue
. -
Hashtable
class implements a hash table, it maps keys to values. Any non-null
target or can be used as key values.
In order to successfully store and retrieve objects from the hash table, the key must be used to achieve the objecthashCode
methods andequals
methods.
JDK1.0 version,Thread SafetyOperating efficiency slow; not allowed to usenull
asKey
eithervalue
. -
TreeMap
The method may speak Map key-value pairs in accordance with the natural ordering of the key-value;
FIG frame set (Map omitted)
Collection of utility methods
In the previous article we mentioned a few simple ways Collection of tools:
method | description |
---|---|
public static void reverse(List<?> list) |
Reversing the order of the elements in a set of |
public static void shuffle(List<?> list) |
Reset random sequence set elements |
public static void sort(List<?> list) |
Ascending order (element must implement Comparable interface) |
Of course, it also provides multiple methods available thread-safe collection:
method | description |
---|---|
static <T> Collection<T> synchronizedCollection(Collection<T> c) |
Returns a collection by the specified collection supports synchronized (thread-safe). |
static <T> List<T> synchronizedList(List<T> list) |
Returned by the specified list of supported list synchronization (thread-safe). |
static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) |
Returned by the specified map mapping support synchronized (thread-safe). |
static <T> Set<T> synchronizedSet(Set<T> s) |
Returned by the specified collection to support synchronized (thread-safe) set. |
static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) |
Returned by the specified sorted map backed synchronized (thread-safe) sorted map. |
static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) |
Returns a synchronized (thread-safe) sorted set by the specified sorted set supports. |
synchronizedList(List list) 为例
Source code analysis
①: After the point in, we will list
pass in, and then a three-judge unary operator according to the type of the random access, the determination result is new
a new object to new SynchronizedList<>(list))
an example;
②: SynchronizedList<>(list))
a method in the user-entered configuration to list
give the parent class, and to list
pay its own attribute final List<E> list;
③: SynchronizedList<>(list))
parent came to pass list
without empty conditions, to keep it final Collection<E> c
, and will get inside a class object mutex
is equivalent to a lock object;
④: when using the method set of operations, here to add
, for example, by using an internal class object method within the class add
, the method must get access to the tag, the party calls further using conventional add
methods (⑤);
overall, through a simple set of original packaging, that is, the addition of a lock object mutex
to guarantee the security thread; ( mutex
is an instance variable, each set is only one of the instance variables)
Security guarantee thread
When a plurality of such method needs to be performed on the set of operations, it is necessary to get the lock flag set can operate, concurrently executing threads may be unsafe original set, a set of thread-safe to upgrade serial implementation;
Acting ideas
As a class we use, we can not meet the current needs of the time, no need to operate the original class, but a class together, enhance its function, which is proxy
the agent; including the now popular Spring
core framework on two: factory + agency;
summary
- JDK1.2 offer, unified interface, high maintenance, but because both use
synchronizedList
a mutex to achieve, so there is no performance improvement; therefore Essentially, the method and the use of Vector and HashTable are not very different;
CopyOnWriteArrayList class
Learn to read and write locks
Learn to read and write lock is essentially a knowledge of the class design pattern, because the type of design patterns and read-write locks are different there are similarities together understanding will be more impressive; providing links on a read-write lock before the relevant :
For read and write operations, the write locks are mutually exclusive, rather than concurrently, rather than mutually exclusive read lock can execute concurrently, so a mutex it, do not write it does not exist, because mutually exclusive, so are not concurrent, compared to this, the read-write locks can greatly improve efficiency.
Source code analysis
First contact with a new class, we should not try to get to know his definition, you need to understand what it is essentially done by reading the source code, then you will know the meaning and origin of its name, this is the most important;
- Write operation (in
add
example)
For a write operation, where a comparison with a clever way, i.e., the current class instance variables getarray
paid to a new array objectelements
, and then modified based on the particular array, i.e.elments
the values assigned tonewElements
, andnewElements
capacity plus one, and then passed ine
(i.e., where the character "a") into the memorynewElements
, and all is ready, and then replaced by a new array directly out of the class instance variablesarray
; &
ESMP; in general, during the addition process data, i.e., write, and no class instance variablesarray
for any operation, but only to create a new object array, then an array of the new target after the operation is completearray
replacement;
when a plurality of writes when the array is operated, because there are reasons for re-entry lock, can only be executed serially, it does not support concurrent ensure the security thread; - Reading Methods
public E get(int index) {
return get(getArray(), index);
}
Obviously not write lock object, but stored directly support the concurrent execution;
CopyOnWriteArrayList exclusive right to read and write?
Obviously not mutually exclusive, thanks to a write operation in the clever design: the time during the write operation that is not a class instance variables ah array
operate, but write in the new array, when the write is complete after a direct replacement; obviously when multiple concurrent read and write operations performed when the process of reading the writing process does not see the digital operation of the operation, so thread-safe, read and write are not mutually exclusive!
Here analogy can update App, such as QQ carrying out an updated version of the time, affect the user do? Obviously not, then the program will ape the new version of the test is completed, the new version of the code will replace the old version, obviously the user when in use, use the function will not be affected, so the analogy here to read and write is not mutually exclusive ;
therefore, the implementation class is not only thread-safe, but under more of a read operation situation, the program will double the efficiency! ! !
how to use?
Use and ArrayList is exactly the same, which also embodies a design pattern: interface reference point to achieve the object class, easier to replace realize, is a good way to decouple
vector与CopyOnWriteArrayList
If the program development process, we need a thread-safe List, try not to use is not recommended Vector
in earlier versions of JDK which we will use Vector
, but because of relatively low efficiency ( Vector
all methods are added to the re-entry lock, mutual exclusion, do not support concurrent), thus providing an efficient thread-safe CopyOnWriteArrayList
after collection classes ( CopyOnWriteArrayList
read and write, read support concurrent), has been gradually phased out of Vector
use;
summary
- Thread-safe ArrayList, enhanced version of the separate read and write (read and write not mutually exclusive);
- Write lock, read no lock, no obstruction between the reader, better than the read-write locks;
- When writing copy to copy a container, adding a new element, and finally replace references.
- ArrayList tantamount to use;
CopyOnWriteArraySet class
CopyOnWriteArraySet underlying implementation is CopyOnWriteArrayList, but List feature is ordered by an index, the elements can not be repeated, the key point: how to re-implement it?
private final CopyOnWriteArrayList<E> al; //底层实现 ArrayList
public CopyOnWriteArraySet() {
al = new CopyOnWriteArrayList<E>();
}
Source code analysis
- In a
add
method, for example, to re-look at the principle of Set
/**
* Appends the element, if not present.
*
* @param e element to be added to this list, if absent
* @return {@code true} if the element was added
*/
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
/**
* A version of addIfAbsent using the strong hint that given
* recent snapshot does not contain e.
*/
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
if (snapshot != current) {
// Optimize for lost race to another addXXX operation
int common = Math.min(snapshot.length, len);
for (int i = 0; i < common; i++)
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= 0)
return false;
}
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
The key code is as follows, and the rest of CopyOnWriteArrayList
similar
For collections thread-safe, there are many, but on the blog post will make readers feel more boring to read, and this blog, I spend a lot more time and energy and hope to receive your thumbs or concerns. thanksgiving! thank! grateful! The other set of thread-safe to be updated ...