http://www.slideshare.net/alexmiller/java-concurrency-gotchas-3666977
并发编程的几个基本topic:
互斥(共享变量,竞争区域)
同步
性能
互斥:
在共享变量的使用上,一是避免共享(threadLocal 变量,local variable即每次新建实例),二是正确的使用lock,注意读写都要加锁(我们常常仅仅对写加锁)
java 中共享变量还有两个issue,一是可见性,为避免OS/JVM优化,每个线程拥有不同副本(?),使用volatile关键字确保仅有一个副本;
二是原子性,注意点,++操作不是原子操作,long(64位变量)的修改非原子性 - 多个线程对同一个long非同步条件下进行++, --,会出现不可预见的结果。
另外高并发条件下,safe publication也是一个问题,常见的错误是在constructor中将this发布出去。保证安全的做法是使用factory method或者避免在construcotr 发布this对象
同步:
最基本的wait, notify, 在loop中wait,必须synchronize即获得对象的锁,才能在对象上wait或者唤醒
1.5后的Lock/Condition,synchronizer(CountDownLatch, CylicBarrier, Semaphore)更灵活简洁
性能:
避免大量线程/状态,使用一个锁,造成锁的竞争。
多使用异步操作。
Topic
- Shared Data
- Locking
- Visibility
- Atomicity
- Safe Publication
- Coordination
- Performance
Shared Data
Lock
Shared Mutable statics
- instance per call
- thread local
- lock
java
- Danger: DateFormat, Calendar, Matcher
- Safe: Random, Pattern
do not synchronize on
- null
- string literals (for scope)
- autoboxed vals (for scope)
Visibility
volatile
Atomicity
Assignment of 64 bit values - volatile
Atomic read for long value
Safe publication
register listener(this) in constructor / starting thread(this) in constructor, use factory method ?
Coordination
Threads
resume()
Wait. Notify
- must synchronize
- Always wait in a loop
Performance
DeadLock avoidance
- lock splitting
- lock ordering
- lock timeout
- tryLock
Spin wait
Condition
Lock contention
Lock striping
Question
both write and read shard value need synchronization ?
alex miller 和我的水平差不多,还是我的水平和alex miller 差不多