问题
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