【7】 常见线程不安全的类与写法

 StringBuilder 不安全

StringBuilder 不安全,但是可以放在方法内局部变量,是堆栈封闭的,

StrinBuffer  安全

synchronized关键字性能损耗,

查看append方法:stringBuffer.append("h");

SimpleDateFormat 不安全,除非定义局部变量堆栈封闭

  public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
public static void dateCall(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            simpleDateFormat.parse("20180903");
        } catch (ParseException e) {
            log.info("解析日期异常");
            e.printStackTrace();
        }
    }

joda-time -SimpleDateFormat- 安全的日期包

    <!--安全的日期类-->
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
	<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>2.9</version>
		</dependency>

实现代码

package com.mmall.concurrency.unsafeClass;

import com.mmall.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


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

@Slf4j
@NotThreadSafe
public class jodaDateTime {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    //  jodaTime
    // public static DateTimeFormatter dateTimeFormatter = new DateTimeFormatter("yyyyMMdd");
    public static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd");

    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();
                    dateCall(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 ");
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            } );
        } // for
        countDownLatch.await();
        executorService.shutdown();

    }

    private static void dateCall(int j){
        log.info("{},{}",j, DateTime.parse("20190723",dateTimeFormatter));
    }
}
jodaDateTime - 4165,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4054,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4046,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4167,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4050,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4169,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4161,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4170,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4033,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4113,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4138,2019-0

最常用的集合数据结构-- 当然有对应安全的


@Slf4j
@NotThreadSafe
public class HashSetDemo {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    public static Set<Integer> set = new HashSet<>();

    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();
                    hash(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 ");
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            } );
        } // for
        countDownLatch.await();
        executorService.shutdown();
        log.info("set不安全:{}",set.size());
    }

    private static void hash(int j){
        set.add(j);
    }
}

接下来看看那些不安全的写法

两个线程同时判断-同时符合-同时处理-线程安全问题

因为两个操作之间有间隔,不是原子性

结局办法 -- 加个锁-  原子性 -- CAS

总结:

*  这几个写法查资料单独学习

ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

*  除了上面提到的几个类,还有很多线程不安全的类

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值