How is it possible for a program to contain exclusively thread-safe classes, but not be thread-safe?

天大地大妈咪最大 提交于 2020-01-30 06:03:46

问题


I am reading "java concurrency in practice", and the author says: "A program that consists entirely of thread-safe classes may not be thread-safe". How is this possible? I don't seem to understand, can someone provide an example?


回答1:


An example would be individual methods on a class that are thread safe, but they are not atomic if you invoke more than one. E.g.

if (!threadSafeCollection.contains(thing)) {
  threadSafeCollection.add(thing);
}

This may yield incorrect results if another thread adds to the collection between the contains and add invocations in this thread.




回答2:


To add a bit more clarity around this question.

From JCIP (statement 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

And what does B Goetz define as thread-safe? (statement 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

My interpretation of these two statements together makes sense if we interpret statement 1 to mean that the class making the calls to entirely thread safe classes is itself not counted as part of the set of classes in the program. Then one can construct a program with check-then-act problems, an operation that should be atomic but is not, for example, in the answer by Andy Turner above.



来源:https://stackoverflow.com/questions/50266807/how-is-it-possible-for-a-program-to-contain-exclusively-thread-safe-classes-but

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!