- 1 Atomicity
- 2 Atomic Statements in Java
- a.Atomic Types
- b.Non-blocking Algorithms
- c.Locks
- d. Counting Semaphore
- e.Barriers
- f. Executor
1 Atomicity
含义:最小的不会被中途插入(interleaving)的单元,换句话说:要么完成,要么不做。
但是也会产生同步错误因为 memory consistency errors
优点:使用atomically 访问可以避免synchronization
使用场景:更高性能,但更难,容易出错,通常在需要高度优化代码时使用。
| operation | doc |
|---|---|
| Reads and writes of reference variables | reference : always object ;holds a reference to information |
| Reads and writes of most primitive variables | Atomic for 32bit values,not sure for float and other type depends on the system |
| Reads and writes of all variables declared volatile | not perform a mutual exclusive lock compare to synchronized |
| Not atomic are multiple, combined accesses | x=y+1; increase and decrease |
Non-blocking含义:一个thread的失败并不能导致其他thread阻塞或失败
Non-blocking Algorithms:allows threads to access shared state (or otherwise collaborate or communicate) without blocking the threads involved.
public class AtomicCounter {
private AtomicLong count = new AtomicLong(0);
public void increment() {
boolean updated = false;
while(!updated){
long prevCount = this.count.get();
updated = this.count.compareAndSet(prevCount, prevCount + 1);
}
}
public long count() {
return this.count.get();
}
}
c.Locks
An option to realize critical sections are locks
reentrant: 一个lock可以进入很多次
Locks: Attempted Acquisition
A synchronized block可以被视作一个lock unlock对,但没有可能退出。
所以提供了 tryLock(),不仅仅lock 还会return有没有成功上锁。
这里的lock只能被local或other其中一个拿到
Semaphore(int capacity, boolean fair)
给临界区一个容capacity,只能进去n次
- acquire(): 进入临界区,n–,阻塞线程
- release():release n++
- tryAcquire(): like acquire() but does not block
- CyclicBarrier(int n) : 可被重复使用,await n 次 resume
- CountDownLatch(int n) :不可被重复使用,以后的countdown 返回迅速
- Exchanger() :Synchronous exchange of two objects between two threads
public class BarrierDemo {
static CyclicBarrier barrier;
public static void main(String[] args) {
barrier = new CyclicBarrier(2);
new Thread(BarrierDemo::runSingleThread).start();
new Thread(BarrierDemo::runSingleThread).start();
}
public static void runSingleThread() {
try {
// Do first task
System.out.println("Reached first barrier");
barrier.await();
// Do second task
System.out.println("Reached second barrier");
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {}
}
}
f. Executor
这个需要单独写一篇。



