java高并发(十)线程不安全类与写法

释放双眼,带上耳机,听听看~!

什么是线程不安全类?

如果一个类的对象同时可以被多个线程访问,如果不做特殊的同步与并发处理,就很容易表现出线程不安全的现象,比如抛出异常,比如逻辑处理错误等,这种类就是线程不安全类。

StringBuilder->StringBuffer


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
1@Slf4j
2public class StringExample1 {
3    // 请求总数
4    public static int clientTotal = 5000;
5
6    // 同时并发执行的线程数
7    public static int threadTotal = 200;
8
9    public static StringBuilder stringBuilder = new StringBuilder();
10
11    public static void main(String[] args) throws InterruptedException {
12        //线程池
13        ExecutorService executorService = Executors.newCachedThreadPool();
14        //定义信号量
15        final Semaphore semaphore = new Semaphore(threadTotal);
16        //定义计数器
17        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
18        for(int i = 0; i < clientTotal; i++) {
19            executorService.execute(() ->{
20                try {
21                    semaphore.acquire();
22                    update();
23                    semaphore.release();
24                } catch (InterruptedException e) {
25
26                    log.error("exception", e);
27                }
28                countDownLatch.countDown();
29
30            });
31        }
32        countDownLatch.await();
33        executorService.shutdown();
34        log.info("size:{}", stringBuilder.length());
35    }
36
37    public static void update() {
38        stringBuilder.append("1");
39    }
40}
41

输出结果与我们预期的不一致。StringBuilder是一个线程不安全的类。 

我们将StringBuilder换成StringBuffer,可以得到预期的效果。说明StringBuffer是线程安全的。

查看StringBuffer的append方法,发现这个方法与其他方法前添加了synchronized关键字。

StringBuffer因为使用了synchronized关键字,因此在使用的时候会有性能损耗的,因此在做字符串拼接时涉及到多线程可以考虑StringBuffer来处理。

但是很多时候,我们往往在一个方法里面做字符串拼接单独,定义一个StringBuilder变量就可以了。因为在一个方法内部定义局部变量时属于堆栈封闭,这时只有单个线程可以操作对象,不涉及到线程安全问题了。

SimpleDateFormat -> JodaTime 


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
1@Slf4j
2public class DateFormatExample1 {
3
4    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
5    // 请求总数
6    public static int clientTotal = 5000;
7
8    // 同时并发执行的线程数
9    public static int threadTotal = 200;
10
11
12    public static void main(String[] args) throws InterruptedException {
13        //线程池
14        ExecutorService executorService = Executors.newCachedThreadPool();
15        //定义信号量
16        final Semaphore semaphore = new Semaphore(threadTotal);
17        //定义计数器
18        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
19        for(int i = 0; i < clientTotal; i++) {
20            executorService.execute(() ->{
21                try {
22                    semaphore.acquire();
23                    update();
24                    semaphore.release();
25                } catch (InterruptedException e) {
26
27                    log.error("exception", e);
28                }
29                countDownLatch.countDown();
30
31            });
32        }
33        countDownLatch.await();
34        executorService.shutdown();
35    }
36
37    public static void update() {
38        try {
39            simpleDateFormat.parse("20190729");
40        } catch (ParseException e) {
41            e.printStackTrace();
42            log.error("parse Exception" + e);
43        }
44    }
45
46}
47

运行时,会抛出异常:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1Exception in thread "pool-1-thread-3" java.lang.NumberFormatException: For input string: "E.177"
2   at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
3   at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
4   at java.lang.Double.parseDouble(Double.java:538)
5   at java.text.DigitList.getDouble(DigitList.java:169)
6   at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
7   at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1867)
8   at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
9   at java.text.DateFormat.parse(DateFormat.java:364)
10  at com.vincent.example.commonUnsafe.DateFormatExample1.update(DateFormatExample1.java:50)
11  at com.vincent.example.commonUnsafe.DateFormatExample1.lambda$main$0(DateFormatExample1.java:34)
12  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
13  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
14  at java.lang.Thread.run(Thread.java:745)
15

这是线程不安全的,simpleDateFormat不是一个线程安全的类,一种解决办法是将SimpleDateFormat simpleDateFormat = new SimpleDateFormat()放到方法内,封闭堆栈,修改update方法如下:


1
2
3
4
5
6
7
8
9
10
1public static void update() {
2        try {
3            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
4            simpleDateFormat.parse("20190729");
5        } catch (ParseException e) {
6            e.printStackTrace();
7            log.error("parse Exception" + e);
8        }
9    }
10

JodaTime是线程安全的:


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
1@Slf4j
2@ThreadSafe
3public class DateFormatExample3 {
4
5    // 请求总数
6    public static int clientTotal = 5000;
7
8    // 同时并发执行的线程数
9    public static int threadTotal = 200;
10
11    private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd");
12
13    public static void main(String[] args) throws InterruptedException {
14        //线程池
15        ExecutorService executorService = Executors.newCachedThreadPool();
16        //定义信号量
17        final Semaphore semaphore = new Semaphore(threadTotal);
18        //定义计数器
19        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
20        for(int i = 0; i < clientTotal; i++) {
21            final int count  = i;
22            executorService.execute(() ->{
23                try {
24                    semaphore.acquire();
25                    update(count);
26                    semaphore.release();
27                } catch (InterruptedException e) {
28
29                    log.error("exception", e);
30                }
31                countDownLatch.countDown();
32
33            });
34        }
35        countDownLatch.await();
36        executorService.shutdown();
37    }
38
39    public static void update(int i) {
40        log.info("{}, {}", i, DateTime.parse("20190729",dateTimeFormatter).toDate());
41    }
42
43}
44

ArrayList,HashSet,HashMap等Collections

通常我们使用这些集合类时他们的对象通常声明在方法里面作为局部变量来使用,很少触发线程不安全的问题,但是一旦定义成static的时候而且多个线程可以进行修改的时候就会容器出问题。例如下面的代码:


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
1@Slf4j
2public class ArrayListExample {
3    // 请求总数
4    public static int clientTotal = 5000;
5
6    // 同时并发执行的线程数
7    public static int threadTotal = 200;
8
9    private static List<Integer> list = new ArrayList<>();
10
11    public static void main(String[] args) throws InterruptedException {
12        //线程池
13        ExecutorService executorService = Executors.newCachedThreadPool();
14        //定义信号量
15        final Semaphore semaphore = new Semaphore(threadTotal);
16        //定义计数器
17        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
18        for(int i = 0; i < clientTotal; i++) {
19            final int count  = i;
20            executorService.execute(() ->{
21                try {
22                    semaphore.acquire();
23                    update(count);
24                    semaphore.release();
25                } catch (InterruptedException e) {
26
27                    log.error("exception", e);
28                }
29                countDownLatch.countDown();
30
31            });
32        }
33        countDownLatch.await();
34        executorService.shutdown();
35        log.info("size:{}",list.size()) ;
36    }
37
38    public static void update(int i) {
39        list.add(i);
40    }
41
42}
43

输出结果不是我们所预期的。

同样适用HashSet,HashMap也无法输出正确的结果。这些都是线程不安全的。

后面会介绍这些集合对应的线程安全类。

先检查在执行 if(condition(a)) {handle(a);}

为什么这种写法是线程不安全的?假设a是线程安全的类,即使if(condition(a))是线程安全的操作,handle(a)也是线程安全的,但是两个结合起来就不是线程安全的了,并不是原子性的。

Atomic类在自增的时候,底层实现是通过CAS原理来保证原子性的跟新。

实际过程中,如果遇到这种情况要判断一个对象是否满足某个条件,然后做某个操作,一定先要考虑这个对象是否多线程共享的,如果是多线程共享的一定要在上面加锁,或者保证操作是原子性的才可以。否则会触发线程不安全的。

转载于:https://my.oschina.net/duanvincent/blog/3080536

给TA打赏
共{{data.count}}人
人已打赏
安全经验

Docker安装gitlab

2021-10-11 16:36:11

安全经验

安全咨询服务

2022-1-12 14:11:49

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索