Java Concurrency Gotchas

本文探讨了Java并发编程中的常见问题,包括互斥、同步及性能优化等关键方面。重点介绍了如何正确使用锁、保证变量可见性和原子性操作,以及安全发布对象的方法。此外,还讨论了如何利用条件变量和锁分割等技术提高并发性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 差不多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FireCoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值