### Concurrency Issues

2. Memory consistency errors

### Thread Interference Errors (Race Conditions)

1. 检索当前count的当前值
2. 检索到的值加1
3. 将增加后的值存储到count

When multiple threads try to read and write a shared variable concurrently, and these read and write operations overlap in execution, then the final outcome depends on the order in which the reads and writes take place, which is unpredictable. This phenomenon is called Race condition.

The section of the code where a shared variable is accessed is called Critical Section.

### Memory Consistency Errors

Memory inconsistency errors occur when different threads have inconsistent views of the same data. This happens when one thread updates some shared data, but this update is not propagated to other threads, and they end up using the old data.

1. Compiler可能对你的程序进行了优化来提升性能。
2. Processors可能尝试进行了优化，比如一个processor可能从temporary register读取变量（含有变量最近一次读取的值），而不是main memory（含有变量最新的值）。

### Synchronization

1. 一次只有一个线程可以读写共享变量。
2. 如果有线程修改了共享变量，它自动与其他随后读写该共享变量的线程建立了happens-before的关系。这保证了完成的修改操作可以被其他线程看到。

Java有synchronized关键字来synchronize access共享变量来避免这些问题。

#### Synchronized Methods

Synchronization的概念通常都会与一个对象绑定。在上述例子中，同一个对象的increment()方法不能被同时多次调用，但是不同对象的increment()方法可以被不同的线程同时调用。

#### Synchronized Blocks

Java使用intrinsic lock或者monitor lock来管理线程的同步。每个对象都有一个与之关联的intrinsic lock

synchronized关键字也可以作为block statement，与synchronized method不同，synchronized statements必须指明提供intrinsic lock的对象：

The idea of allowing a thread to acquire the same lock more than once is called Reentrant Synchronization.

### Volatile Keyword

Volatile keyword用来避免多线程程序中的memory consistency errors。它告诉compiler不要对变量做优化，compiler不会优化或者重排序该变量的指令。