Concurrency Programming Digest 1
Yehan(Davis) Zhang
A huge fan of data intensive App! Voyage starts from OLAP @ Redshift -> Datalake @ Onehouse.
A state can be made?concurrent safe via:
A mutable state is guarded by a lock when:
Use invariants to define the correctness.
? ??+ [same state, same lock]?Every shared, mutable state should be guarded?by exactly one lock.
We can optionally?use atomic/volatile counterparts?for states that
- Only captured by?single-state invariants
- All updates?are not compound?(e.g.?increment, CAS)
Never use raw basic data types without synchronization.?Especially if the access?is done?in a multi-step fashion (such as read then act), use a lock.
Out-of-thin-air safety:
When a thread reads a variable without synchronization, it may see a stale value, but at least it sees a value?that was?placed there by some thread rather than some random value. This safety guarantee is called?out-of-thin-air safety.
One exception: 64-bit numeric variables (double and long) that are not declared volatile?(see Section 3.1.4).?The Java Memory Model requires fetch and store operations to be atomic, but for?nonvolatile long and double variables, the JVM?is permitted?to?treat a 64-bit read or write as two separate 32-bit operations. If the reads and writes occur in different threads, it is?therefore possible?to read a nonvolatile long and get back the high 32 bits of one value and the low 32 bits of another.
A class is thread-safe if the invariant always holds when
- accessed from multiple threads, regardless of how executions?are interleaved
- no additional coordination from the client code
Race condition:
- Time of check is not time of use
Atomicity:
Operation A and B are atomic?with respect to?each other if, from the perspective of a thread executing A, when another thread executing B, either all or none of B has executed.
### Locks:
Every Java object can implicitly act as a lock for?the purpose of?synchronization. These built-in locks are called intrinsic locks or monitor locks.
```
synchronized (lock) {
? ??// access shared state guarded by the lock
}
```
To avoid poor concurrency, limit?the critical section to its absolute needed scope.
Reentrancy: a thread can repeatedly acquire locks?that?are?already acquired?by the same thread.
Avoid holding locks during lengthy computations or blocking?operations like?network or console I/O.
Reference: <<Java concurrency in practice>> Chapter 2