Java Concurrency Gotchas

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

### Java 并发编程中的多线程同步与锁 #### synchronized 关键字 `synchronized` 是 Java 中最基本也是最常用的同步机制之一。此关键字可用于修饰方法或代码块,确保在同一时刻仅有一个线程能执行相应的方法或代码片段[^1]。 ```java public class Counter { private int count; public synchronized void increment() { // 同步整个方法 this.count++; } public void decrement() { synchronized (this) { // 或者只同步部分代码块 this.count--; } } } ``` #### 自旋锁(Spin Lock) 除了 `synchronized`,另一种常见的锁定策略是在 JDK 1.5 版本引入的自旋锁。当某个线程尝试获取已被占用的锁时,不会立即进入阻塞状态而是会持续循环检查锁的状态直至获得锁为止。这种方式适用于竞争不激烈且持有时间较短的情况,在某些场景下可减少上下文切换带来的开销[^2]。 ```java class SpinLockDemo { private final AtomicReference<Thread> sign = new AtomicReference<>(); public void lock() { Thread current = Thread.currentThread(); while (!sign.compareAndSet(null, current)) {} } public void unlock() { Thread current = Thread.currentThread(); sign.compareAndSet(current, null); } } ``` #### 使用 ThreadLocal 避免竞态条件 为了进一步简化并发环境下的数据管理并提升效率,Java 还提供了 `ThreadLocal` 类型来为每个线程创建独立的数据副本。这不仅解决了传统意义上的资源争抢问题,同时也降低了因频繁加解锁操作而造成的性能损耗[^3]。 ```java public class Task implements Runnable { private static final ThreadLocal<Integer> threadLocalValue = ThreadLocal.withInitial(() -> 0); @Override public void run() { Integer value = threadLocalValue.get(); // 获取当前线程独有的值 System.out.println(Thread.currentThread().getName() + " has value: " + value); try { Thread.sleep(100); // 模拟耗时任务 } catch (InterruptedException e) {} threadLocalValue.set(value + 1); // 更新当前线程独有值 System.out.println(Thread.currentThread().getName() + " updated to : " + threadLocalValue.get()); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

FireCoder

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

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

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

打赏作者

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

抵扣说明:

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

余额充值