HashMap 1.8的源码分析三

线程安全问题:

在添加时候并没有进行安全考虑,枷锁

所以是线程不安全的,接下来进行代码测试;

package com.mmall.concurrency.example.commonUnsafe;

import com.mmall.concurrency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;


public class HashMapExample {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    private static Map<Integer, Integer> map = new HashMap<>();

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int count = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update(count);
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception" , e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(map.size());
        log.info("size:{}" , map.size());
    }

    private static void update(int i) {
        map.put(i, i);
    }
}

运行三次:

所以hashmap是线程不安全的,那么我们在代码里面怎么还要用呢,我们只是局部使用,并没有在多线程环境下使用,所以并不会出现线程安全问题

 

posted @ 2019-01-30 14:37  菩提树下的丁春秋  阅读(95)  评论(0编辑  收藏  举报