java线程不安全类与写法
线程不安全类
1.为什么java里要同时提供stringbuilder和stringbuffer两种字符串拼接类
2.simpledateformate是线程不安全的类,如果把它作为全局变量会有线程安全的问题,根据线程封闭原则,把它作为局部变量就可以了,或者用jodatime
jodatime使用示例
package com.alan.concurrency.example.commonUnsafe; import com.alan.concurrency.annoations.ThreadSafe; 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 @ThreadSafe public class DateFormatExample3 { // 请求总数 public static int clientTotal = 5000; // 同时并发执行的线程数 public static int threadTotal = 200; private 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(); update(count); semaphore.release(); } catch (Exception e) { log.error("exception", e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); } private static void update(int i) { log.info("{}, {}", i, DateTime.parse("20180208", dateTimeFormatter).toDate()); } }
3.arraylist hashset hashmap
2.不安全的写法
1.先检查再执行 if(condition(a)){handle(a);} --要注意这个a是否会被多个线程共享修改,解决办法是锁+双重验证
2.vector并不是所有情况下都是线程安全的,例如两个线程,一个get,一个remove,如果同一下标的值是先remove,那么get时就会出错。