06章 线程安全策略

不可变对象

对象创建以后其状态就不能修改
对象所有域都是final类型
对象是正确创建的(在对象创建期间,this引用没有溢出)

final关键字:类、方法、变量

修饰类:不能被继承
修饰方法:1. 锁定方法不被继承类修改;2. 效率
修饰变量:基本数据类型变量、引用类型变量

线程封闭

堆栈封闭: 局部变量,无并发问题
ThreadLocal线程封闭:特别好的封闭方法

线程不安全类与写法

StringBuilder -> StringBuffer
SimpleDateFormat -> JodaTime
ArrayList,HashSet, HashMap 等 Collections

线程安全 - 同步容器

Arraylist -> Vector, Stack
HashMap -> HashTable(key、value不能为null)
Collections.synchronizedXXX(List,Set,Map)
同步容器主要是通过synchronized关键字实现线程安全

线程安全 - 并发容器J.U.C

线程安全 - 并发容器 J.U.C
ArrayList -> CopyOnWriteArrayList
HashSet、TreeSet -> CopyOnWriteArraySet、ConcurrentSkipListSet
HashMap、TreeMap -> ConcurrentHashMap、ConcurrentSkipListMap

猜你喜欢

转载自blog.csdn.net/weixin_34146805/article/details/87120583