Home Common Problem Is hashset thread safe?

Is hashset thread safe?

Apr 25, 2019 pm 01:38 PM
hashset

What is thread safety? It means that the reading and writing of data must be thread-isolated, and data loss and inconsistency cannot be caused. Data should not be overwritten every time it is modified.

Let’s take the classic example of bank withdrawal. Account A is initially 0, thread A reads 0, and then saves 100 (no data has been written yet). Thread B reads 0 and also saves 100. At this time The last account we see is a balance of 100. This is unscientific and is called thread unsafe. Therefore, we need to control the objects for deposits and withdrawals, and let the objects we operate data lock. After updating the data, other threads can achieve thread safety.

Is hashset thread safe?

This time we will prove HashSet, we know that the Set interface is implemented. The characteristic of Set is that the data stored will not be repeated. Because it will first read the internally saved data to see if it exists. If it exists, it will not be stored in it, otherwise it will be stored in it. In other words, the data storage operation is divided into two steps, first reading, and then writing. Assuming that it is not thread-safe, a very likely situation is that when thread A determines that the set object does not have an element and is about to insert the element, thread B also determines that the object does not have the element and is also preparing to insert it. Finally, The result is that two identical elements are inserted.

We design the demo like this:

class TestHashSet implements Runnable{
    // 实现Runnable 让该集合能被多个线程访问
    Set<Integer> set = new HashSet<Integer>();
    // 线程的执行就是插入5000个整数
    @Override
    public void run() {
        for (int i = 0;i < 5000;i ++) {
            set.add(i);
        }
    }
}
Copy after login

We test it on the main thread:

  TestHashSet run2 = new TestHashSet();
        // 实例化两个线程
        Thread t6 = new Thread(run2);
        Thread t7 = new Thread(run2);
        // 启动两个线程
        t6.start();
        t7.start();
        // 当前线程等待加入到调用线程后
        t6.join();
        t7.join();
        // 打印出集合的size
        System.out.println(run2.set.size());
Copy after login

Most of the printed results are the expected 5000, but occasionally there will be a situation greater than 5000 . This leads to the situation mentioned before, which proves that HashSet is not a thread-safe class.

In fact, looking at the source code, we found that HashMap is used to maintain data internally in HashSet. The fundamental reason is that HashMap is not a thread-safe class. This leads to the non-thread safety of HashSet. For more knowledge about Java collection classes, please pay attention to [PHP Chinese website: java video]

Finally, a complete code case verification:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 验证HashSet不是线程安全
 */
public class HashSetTest {
    public static void main(String[] args) {
        final Set<Integer> set = new HashSet<>();// 结果可能大于1000
//        final Set<Integer> set = Collections.synchronizedSet(new HashSet<>());// 结果等于1000
//        final Set<Integer> set = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());// 结果等于1000
        // 往set写入1-1000
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 1000; i++) {
                    set.add(i);
                }
            }
        };
        int threadNum = 10;// 线程数
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(runnable);
            threadList.add(thread);
            thread.start();
        }
        // 主线程等待子线程执行完成
        for (Thread thread : threadList) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(set.size());// 结果可能大于1000
    }
}
Copy after login

The above is the detailed content of Is hashset thread safe?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use HashSet.remove() method in Java to remove elements from a collection? How to use HashSet.remove() method in Java to remove elements from a collection? Nov 18, 2023 pm 02:17 PM

Use the HashSet.remove() method in Java to remove specified elements from a collection. HashSet is a collection class that implements the Set interface. It does not allow the storage of duplicate elements and does not guarantee the order of elements. When operating a HashSet, you can use the remove() method to delete elements in the set. The remove() method of HashSet has two overloaded forms: booleanremove(Objectobj): removes the specified object from the collection

How to use the HashSet function for set operations in Java How to use the HashSet function for set operations in Java Jun 26, 2023 pm 05:15 PM

The HashSet function in Java is a collection class implemented based on a hash table. Since it is a collection class, it naturally has the function of collection operations. This article will introduce how to use the HashSet function to perform collection operations. 1. Definition and declaration of HashSet HashSet is a collection class, so you need to import the Java.util package first. importjava.util.HashSet; Then you can create a HashSet instance: HashSet&lt;

Interpretation of Java documentation: Detailed explanation of the usage of the contains() method of the HashSet class Interpretation of Java documentation: Detailed explanation of the usage of the contains() method of the HashSet class Nov 04, 2023 am 11:43 AM

Interpretation of Java documentation: Detailed explanation of the usage of the contains() method of the HashSet class. The HashSet class is one of the commonly used collection classes in Java. It implements the Set interface and is based on the hash table data structure, with efficient insertion, deletion and search operations. Among them, the contains() method is an important method provided by the HashSet class, which is used to determine whether the set contains the specified element. This article will analyze in detail the usage of the contains() method of the HashSet class, and

Add all elements from one collection to another using the addAll() method of the HashSet class Add all elements from one collection to another using the addAll() method of the HashSet class Jul 24, 2023 am 08:58 AM

Use the addAll() method of the HashSet class to add all elements in a collection to another collection. HashSet is an implementation class in the Java collection framework. It inherits from AbstractSet and implements the Set interface. HashSet is an unordered set based on a hash table, which does not allow duplicate elements. It provides many commonly used methods to operate elements in the collection, one of which is the addAll() method. The function of the addAll() method is to add the specified

How to use HashSet.add() method to add elements to a collection in Java? How to use HashSet.add() method to add elements to a collection in Java? Nov 18, 2023 pm 04:56 PM

It is very simple to add elements to a collection using the HashSet.add() method in Java. Let’s introduce it in detail below. HashSet is a collection class in Java. It inherits from the AbstractSet class and implements the Set interface. The characteristics of HashSet are unordered and non-repeating, and the underlying implementation is based on a hash table. When using the HashSet.add() method to add elements, you need to pay attention to the following points: HashSet can only store elements of object type, not

Add a collection to another collection using the addAll() method of the HashSet class Add a collection to another collection using the addAll() method of the HashSet class Jul 25, 2023 pm 05:00 PM

Use the addAll() method of the HashSet class to add a collection to another collection. HashSet is a collection class in Java. It implements the Set interface and is implemented based on a hash table. Duplicate elements are not allowed in the HashSet collection, and the elements in the collection are unordered. In development, we often need to add elements from one collection to another collection. The HashSet class provides the addAll() method to easily implement this function. Below we will go through a

How to add traversal elements to Java HashSet How to add traversal elements to Java HashSet Apr 28, 2023 pm 01:04 PM

HashSet class diagram HashSet brief description 1. HashSet implements the Set interface 2. The bottom layer of HashSet is actually implemented by HashMap publicHashSet(){map=newHashMap();} 3. Null can be stored, but there can only be one null 4.HashSet does not Ensure that the elements are in order (that is, the order in which the elements are stored is not guaranteed to be the same as the order in which the elements are taken out). The result of the index is determined after hashing. 5. There cannot be duplicate elements. The underlying mechanism of HashSet explains that the bottom layer of HashSet is HashMap, and the bottom layer of HashMap is HashMap. It is the structure of array + linked list + red-black tree simulation array + linked list /*

Interpretation of Java documentation: Detailed explanation of the usage of iterator() method of HashSet class Interpretation of Java documentation: Detailed explanation of the usage of iterator() method of HashSet class Nov 03, 2023 am 09:44 AM

Interpretation of Java documentation: Detailed explanation of the usage of the iterator() method of the HashSet class. Specific code examples are required. In Java programming, HashSet is one of the commonly used collection classes. It implements the Set interface and inherits from the AbstractSet class. The iterator() method of the HashSet class is used to return an iterator object for traversing the elements in the HashSet. This article will explain in detail the usage of iterator() method of HashSet class, and