线程安全

ThreadSafe and NotThreadSafe

Thread safety can be unexpectedly subtle because, in the absence of sufficient
synchronization, the ordering of operations in multiple threads is unpredictable
and sometimes surprising.

线程安全因为没有足够的同步机制可能会产生不可预测甚至出人意料的效果,下面的代码在多线程中可能产生异常。
代码的本意是产生一个整型数字序列,但是多线程的情况下可能出现数字重复的情况

1
2
3
4
5
6
7
8
9
10
@NotThreadSafe
public class UnsafeSequence {
private int value;

public int getNext() {
return value++;
}

}


figure 1.1展示了多线程情况下可能出现的问题
figure 1.1

The problem with UnsafeSequence is that with some unlucky timing, two
threads could call getNext and receive the same value. Figure 1.1 shows how this
can happen. The increment notation, someVariable++,may appear to be a single
operation, but is in fact three separate operations: read the value, add one to
it, and write out the new value. Since operations in multiple threads may be
arbitrarily interleaved by the runtime, it is possible for two threads to read the
value at the same time, both see the same value, and then both add one to it.
The result is that the same sequence number is returned from multiple calls in
different threads.

自增1的操作,看以来像是一个操作,其实分为三部分:

  1. 读数值
  2. 将读出的数值加1
  3. 写数值

如果两个线程在同一时间读出了相同的数值,则加1之后会出现两个相同的数字


作者

Bruce Liu

发布于

2018-11-01

更新于

2022-11-12

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.