Home > Java > Javagetting Started > body text

In-depth understanding of the thread safety of various collections in Java

青灯夜游
Release: 2019-11-28 17:45:44
forward
2109 people have browsed it

In-depth understanding of the thread safety of various collections in Java

Thread safety

First of all, we must understand the working principle of threads. The jvm has a main memory, and each thread It 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 suitable, such as methods, and then lock the monitor to achieve thread safety. Each thread After acquiring this lock, the process of load to workingmemory -> use&assign -> store to mainmemory will be executed before the lock it acquires is released. 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.

【Recommended learning:

java video tutorial

java related collection

Vector, ArrayList, LinkedList

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

Vector's methods are all synchronized (Synchronized) and thread-safe, while ArrayList's methods are not. Since thread synchronization will inevitably affect performance, ArrayList's performance is better than Vector's .

The difference between ArrayList and LinkedList

For processing a column of data items, Java provides two classes, ArrayList and LinkedList. The internal implementation of ArrayList is based on the 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.

It can be seen from the above analysis that when inserting data in front or in the middle of ArrayList, you must move all the subsequent data back accordingly, which will inevitably take more time. Therefore, when your operation is When adding data after a column of data instead of in the front or middle, and you need to access the elements randomly, using ArrayList will provide better performance

And when accessing an element in a linked list, you must Start from one end of the linked list and search element by element 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 access the elements in order When, you should use LinkedList.

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

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.

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 a Key comparison method or passing in a Comparator Implementation, or the key object implements the Comparable interface.

2. TreeMap is not thread-safe.

Summary

The above is the entire content of this article on the detailed explanation of the thread safety of various Java collections. I hope it will be helpful to everyone.

This article comes from the java introduction column, welcome to learn!

The above is the detailed content of In-depth understanding of the thread safety of various collections in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:word666.com
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