界: Time and State

分布式计算是关于时间和状态的。也就是说,为了让多个组件相互通信,必须共享状态,所有这些都需要时间。

大多数程序员都会将其工作拟人化。他们会让一个控制线程以同样的方式(他们必须自己完成工作时采取的方式)执行整个程序。然而,现代计算机不同任务之间切换得非常快,在多核、多 CPU 或分布式系统中,两个事件可能完全同时发生。程序员预期的程序执行过程与实际情况之间存在差距,即存在缺陷。这些缺陷与线程、流程、时间和信息之间的意外交互有关。这些交互是通过共享状态发生的:信号量、变量、文件系统,以及总而言之,可以存储信息的任何内容。

Code Correctness: Double-Checked Locking

Abstract
Double-checked locking 是一种不正确的用法,并不能达到预期目标。
Explanation
许多才智卓越的人都试图使用 double-checked locking 方法来提高性能,并为此付出了大量的时间,但是无一成功。

例 1:乍一看,下列代码似乎既能避免不必要的同步又能保证线程的安全性。


if (fitz == null) {
synchronized (this) {
if (fitz == null) {
fitz = new Fitzer();
}
}
}
return fitz;


程序员希望保证仅分配一个 Fitzer() 对象,但又不希望每次调用该代码时都进行一次同步。这就是所谓的 double-checked locking 方法。

令人遗憾的是,它并不起作用,并且可以分配多个 Fitzer() 对象。有关更多详细信息,请参见 The "Double-Checked Locking is Broken" Declaration [1]。
References
[1] D. Bacon et al. The "Double-Checked Locking is Broken" Declaration
[2] LCK10-J. Use a correct form of the double-checked locking idiom CERT
[3] Standards Mapping - CIS Azure Kubernetes Service Benchmark 1
[4] Standards Mapping - CIS Amazon Elastic Kubernetes Service Benchmark 3
[5] Standards Mapping - CIS Amazon Web Services Foundations Benchmark 1
[6] Standards Mapping - CIS Google Kubernetes Engine Benchmark normal
[7] Standards Mapping - Common Weakness Enumeration CWE ID 609
[8] Standards Mapping - Payment Card Industry Data Security Standard Version 3.0 Requirement 6.5.6
[9] Standards Mapping - Payment Card Industry Data Security Standard Version 3.2 Requirement 6.5.6
[10] Standards Mapping - Payment Card Industry Data Security Standard Version 3.2.1 Requirement 6.5.6
[11] Standards Mapping - Payment Card Industry Data Security Standard Version 3.1 Requirement 6.5.6
[12] Standards Mapping - Payment Card Industry Software Security Framework 1.0 Control Objective 4.2 - Critical Asset Protection
[13] Standards Mapping - Payment Card Industry Software Security Framework 1.1 Control Objective 4.2 - Critical Asset Protection
[14] Standards Mapping - Payment Card Industry Software Security Framework 1.2 Control Objective 4.2 - Critical Asset Protection
desc.structural.java.code_correctness_double_checked_locking