线程之间的“竞争条件”:作用于同一个mutable数据上的多个线程,彼此之间存在对该数据的访问竞争并导致interleaving,导致post-condition可能被违反,这是不安全的。
线程安全:ADT或方法在多线程中要执行正确。
一、Confinement 限制数据共享
核心思想:线程之间不共享mutable数据类型
避免使用全局变量
二、Immutability 共享不可变数据
使用不可变数据类型和不可变引用,避免多线程之间的race condition。
对于并发编程,这种隐藏的变化有时是不安全的,如果ADT中使用了beneficent mutation,必须要通过“加锁”机制来保证线程安全。
以下是对不变性的更强有力的定义:
– No mutator methods
– All fields are private and final
– No representation exposure
– No mutation whatsoever of mutable objects in the rep – not
even beneficent mutation