HashSet 源码分析及线程安全问题

Set 集合最常见的实现类就是 HashSet,就以它为例来讲。底层使用的是 HashMap 进行存储数据,所以了解 HashMap 真正看懂 HashSet 源码。

1. HashSet 的定义详解

  • 定义很简单,继承抽象set,实现接口Set,可复制、可序列化
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable

1.1 HashSet 的构造函数

  • HashSet 有五个构造函数,可以指定初始集合,初始容量,初始的负载因子,但没有三个同时指定的构造函数
/* 空构造,默认初始容量16,负载因子 0.75,后面详解 */
public HashSet() {
    map = new HashMap<>();
}

/** 初始化一个集合,默认负载因子为0.75,容量看情况定义足够存储的大小 */
public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}

/* 创建一个空集合,但是指定 容量大小 与 负载因子 */
public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}

/* 构建空集合,指定 容量大小,使用默认的 负载因子 0.75 */
public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
}

/* 不对外开放的构造函数,指定 容量大小 与 负载因子,参数 dummy 只是为了重载构造,没有意义  */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

1.2 HashSet 的属性定义

  • 只有三个属性:版本(用于序列化),map(底层存储的key,value),PRESENT(用于作为map的值,与null区分)
static final long serialVersionUID = -5024744406713321676L;
/* set 的缓冲数据存储 */
private transient HashMap<E,Object> map;
/* PRESENT 空对象作为 hashmap 的value,不使用 null 是为了与获取key为null区分开 */
private static final Object PRESENT = new Object();

2 操作函数

2.1 add()

  • 调用 HashMap 的 put 方法。
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

2.2 size()

  • 返回 map 的size
public int size() {
    return map.size();
}

2.3 isEmpty()

  • 判断是否为空,根据 map.size == 0 返回结果
public boolean isEmpty() {
    return map.isEmpty();
}
public boolean isEmpty() {
   return size == 0;
}

2.4 contains()

  • 是否包含某个元素
public boolean contains(Object o) {
    return map.containsKey(o);
}

2.5 remove()

  • map.remove(o) 返回的是删除元素的 value 值
public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}

2.6 clear()

  • 调用的是 map.clear()
public void clear() {
    map.clear();
}

2.7 iterator()

  • 调用 map 的 key 遍历器
public Iterator<E> iterator() {
    return map.keySet().iterator();
}

2.8 spliterator()

  • 调用 map 的 key 分解迭代器
public Spliterator<E> spliterator() {
    return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0);
}

2.9 总结

  • HashSet 实际上就是使用 HasMap 的 key 来完成的存储不重复元素。也就是说,想学好 HashSet,学会 HashMap 就可以了。

3. HashSet 线程安全吗?

  • HashMap 线程不安全,HashMap 肯定也不安全。
import java.util.HashSet;
import java.util.concurrent.*;

public class ThreadSetTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());
        CountDownLatch countDownLatch = new CountDownLatch(10);
        HashSet<Integer> hashSet = new HashSet<>();
        for(int i = 1; i <= 10; i++) {
            int finalI = i;
            threadPoolExecutor.execute(() -> {
                for(int j = 1; j <= 10; j++) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    hashSet.add(finalI * 10 + j);
                };
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println("hashSet.size(): " + hashSet.size());
        System.out.println("hashSet: ");
        int num = 0;
        for (Integer integer : hashSet) {
            System.out.print(integer + "\t");
            if(++num >= 10) {
                num = 0;
                System.out.println();
            }
        }
    }
}
  • size变小,元素个数变少,具体原因分析可看 HashMap 篇,这里不做赘述。
    在这里插入图片描述

3.1 线程安全解决

  • 使用 Collections.synchronizedSet()
package cn.cerish.container.collection.set;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadSafeResolveTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());
        Set<Integer> hashSet = Collections.synchronizedSet(new HashSet<Integer>());
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for(int i = 1; i <= 10; i++) {
            int finalI = i;
            threadPoolExecutor.execute(() -> {
                for(int j = 1; j <= 10; j++) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    hashSet.add(finalI * 10 + j);
                };
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println("hashSet.size(): " + hashSet.size());
        System.out.println("hashSet: ");
        int num = 0;
        for (Integer integer : hashSet) {
            System.out.print(integer + "\t");
            if(++num >= 10) {
                num = 0;
                System.out.println();
            }
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值