What are the ways to implement thread safety for Map in Java?
Apr 19, 2023 pm 07:52 PMMethod 1. Use Hashtable
1 |
|
This is the first thing everyone thinks of, so why is it thread-safe? Then take a look at its source code. We can see that our commonly used methods such as put, get, and containsKey are all synchronous, so it is thread-safe.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
The implementation principle is to add, delete, modify, and check. The synchronized lock mechanism is used. In a multi-threaded environment, whether it is reading data or modifying data, only one thread can execute the synchronize method at the same time because the entire table is locked. Therefore, the more threads there are, the more intense the competition for the map and the lower the efficiency. It is not recommended.
Method 2. Use Collections.synchronizedMap(new Hashtable())
The implementation principle is to use the static method in the tool class to package the incoming Hashtable into a synchronized one, that is, in The synchronized mechanism is added to the method of adding, deleting, modifying, and checking. Its implementation is similar to that of Hashtable, and its efficiency is similar. It is not recommended to use.
1 |
|
The following is the JDK source code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
|
Method 3. Use ConcurrentHashMap
The implementation principle is that Hashtable locks the entire table, while ConcurrentHashMap segments the table , initially divided into 16 segments, each segment has a lock. When multiple threads access different segments, because the locks obtained are different, they can be accessed in parallel. The efficiency is much higher than Hashtable, so it is recommended to use it.
The above is the detailed content of What are the ways to implement thread safety for Map in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Break or return from Java 8 stream forEach?
