一个程序怎么可能只包含线程安全的类,而不是线程安全的?
How is it possible for a program to contain exclusively thread-safe classes, but not be thread-safe?
我正在阅读"java concurrency in practice",作者说:"A program that consists entirely of thread-safe classes may not be thread-safe"。这怎么可能?好像没看懂,谁能举个例子?
一个例子是 class 上的单个方法是线程安全的,但如果您调用多个方法,它们就不是原子的。例如
if (!threadSafeCollection.contains(thing)) {
threadSafeCollection.add(thing);
}
如果另一个线程在该线程的 contains
和 add
调用之间添加到集合中,这可能会产生不正确的结果。
为了更清楚地说明这个问题。
来自 JCIP(声明 1):
Is a thread safe program one that is constructed entirely of thread safe classes? Not necessarily, a program that consists entirely of thread safe classes may not be thread safe, and a thread safe program may contain classes that are not thread safe. PP 17
B Goetz 将什么定义为线程安全的? (声明 2)
A class is thread safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code. PP 18
如果我们将语句 1 解释为意味着 class 调用完全线程安全的 classes 本身不计入集合的一部分,那么我对这两个语句的共同解释是有意义的程序中的 classes。然后可以构造一个程序,其中包含先检查后执行的问题,该操作应该是原子的,但不是,例如,在上面 Andy Turner 的回答中。
我正在阅读"java concurrency in practice",作者说:"A program that consists entirely of thread-safe classes may not be thread-safe"。这怎么可能?好像没看懂,谁能举个例子?
一个例子是 class 上的单个方法是线程安全的,但如果您调用多个方法,它们就不是原子的。例如
if (!threadSafeCollection.contains(thing)) {
threadSafeCollection.add(thing);
}
如果另一个线程在该线程的 contains
和 add
调用之间添加到集合中,这可能会产生不正确的结果。
为了更清楚地说明这个问题。
来自 JCIP(声明 1):
Is a thread safe program one that is constructed entirely of thread safe classes? Not necessarily, a program that consists entirely of thread safe classes may not be thread safe, and a thread safe program may contain classes that are not thread safe. PP 17
B Goetz 将什么定义为线程安全的? (声明 2)
A class is thread safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code. PP 18
如果我们将语句 1 解释为意味着 class 调用完全线程安全的 classes 本身不计入集合的一部分,那么我对这两个语句的共同解释是有意义的程序中的 classes。然后可以构造一个程序,其中包含先检查后执行的问题,该操作应该是原子的,但不是,例如,在上面 Andy Turner 的回答中。