Home > Java > javaTutorial > body text

Thread safety analysis of various collections in Java

黄舟
Release: 2017-10-12 10:05:52
Original
1190 people have browsed it

This article mainly introduces the thread safety of various Java collections in detail. The editor thinks it is quite good, so I will share it with you here for the reference of friends who need it.

Thread safety

First of all, we must understand the working principle of threads. JVM has a main memory, and each thread has its own working

memory, when a thread operates on a variable, it must create a copy in its own working

memory, and then write it to main after the operation is completed

memory. If multiple threads operate on the same variable at the same time, unpredictable results may occur. Based on the above explanation, it is easy to come up with the corresponding scenario.

The key to using synchronized is to create a monitor. This monitor can be the variable to be modified or other objects you think are appropriate, such as methods, and then lock the monitor to achieve thread safety. After each thread obtains this lock, it must complete the process of load to workingmemory -> use&assign -> store to mainmemory before releasing the lock it obtained. This achieves so-called thread safety.

What is thread safety? How is thread safety achieved (principle)? Thread safety means that multiple threads access the same code without producing uncertain results. Writing thread-safe code is low on thread synchronization.

java related collection

Vector, ArrayList, LinkedList

##Vector and ArrayList They are very similar in use and can be used to represent a set of variable number of object applications, and the elements can be accessed randomly.


The methods of Vector are all synchronized (Synchronized) and thread-safe, but the methods of ArrayList are not. Since thread synchronization will inevitably affect performance, therefore, the performance of ArrayList Better than Vector.


The difference between ArrayList and LinkedList

For processing a list of data items, Java provides two classes, ArrayList and LinkedList. The internal implementation of ArrayList is based on Internal array Object[], so conceptually, it is more like an array, but the internal implementation of LinkedList is based on a set of connected records, so it is more like a linked list structure, so there is a big difference in performance between them. .


From the above analysis, we can see that when inserting data in front or in the middle of ArrayList, you must move all the data behind it accordingly, which will definitely take more time, so when you The operation is to add data after a column of data instead of in the front or middle, and when you need to randomly access the elements, using ArrayList will provide better performance


  And when accessing a certain element in the linked list When there are elements, you must start from one end of the linked list and search for elements one by one along the connection direction until you find the required element. Therefore, when your operation is to add or delete data in front or in the middle of a column of data, and When accessing the elements in order, you should use LinkedList.


If in programming, the two situations 1 and 2 appear alternately, then you can consider using a general interface like List without caring about the specific implementation. In specific situations, it The performance is guaranteed by the specific implementation.


HashTable,HashMap,HashSet

HashTable and HashMap use the same storage mechanism, and their implementation is basically the same. The difference is:


1), HashMap is not thread-safe, HashTable is thread-safe, and the internal methods are basically synchronized.


2), HashTable does not allow null values ​​to exist.


When calling the put method in HashTable, if the key is null, a NullPointerException will be thrown directly. There are other subtle differences, such as the size of the initialized Entry array, etc., but the basic idea is the same as HashMap.


HashSet:

1. HashSet is implemented based on HashMap and has no capacity limit.


2. HashSet is not thread-safe.


3. HashSet does not guarantee order.


HashMap:

1. HashMap uses an array to store the Entry object composed of key and value, with no capacity limit.


2. HashMap searches for the location where the Entry object is stored in the array based on the Key hash, and uses a linked list to resolve hash conflicts.


3. HashMap may need to expand the capacity of the array when inserting elements. When expanding the capacity, the hash needs to be recalculated and the object copied to a new array.


4. HashMap is not thread-safe.


5. HashMap traversal uses Iterator


HashTable

1. HashTable is thread-safe.


2. Neither Key nor Value in HashTable is allowed to be null.


3. HashTable traversal uses Enumeration.


TreeSet,TreeMap


TreeSet:

1. TreeSet is implemented based on TreeMap and supports sorting.


2. TreeSet is not thread-safe.


Judging from the description of HashSet and TreeSet, TreeSet, like HashSet, is completely based on Map, and neither supports get(int) to obtain the element at the specified position (needs to traverse to obtain). In addition, TreeSet also provides Some sorting support has been added. For example, pass in the Comparator implementation, descendingSet, descendingIterator, etc.

TreeMap:

1. TreeMap is a typical Map implementation based on red-black trees, so it requires Key comparison. Method, either pass in the Comparator implementation, or the key object implements the Comparable interface.

2. TreeMap is not thread-safe.

Summarize

The above is the detailed content of Thread safety analysis of various collections in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template