It's more like hypothetical question that if a program consists entirely of thread safe classes, can we assume it is thread safe program? In what case such program may not be thread safe program?
-
4Does this answer your question? https://stackoverflow.com/a/50266926/12609572 – ardenit Jan 19 '20 at 04:51
1 Answers
A glib answer here would be that no program consists entirely of thread-safe classes, because every program includes the classes of the JDK, of which many are not thread-safe. So any statement of the form "If a program consists entirely of thread-safe classes, […]" is vacuously true by the principle of explosion.
A somewhat more informative answer, albeit still somewhat glib, is that any program is run by calling a public static main
method in some class, and it probably wouldn't be meaningful to call that class "thread-safe" if invocations of that method had threading bugs.
But the deeper answer here is that thread-safety is really a property of a whole program. When we say that a given class is "thread-safe", or (more properly) that instances of a given class are "thread-safe", all we usually mean is that the class is designed to maintain its invariants even when used concurrently from multiple threads, whereas the default assumption in Java is that objects are allowed to completely violate their usual contracts when multiple threads use them without any external synchronization. That is incredibly helpful in building thread-safe programs, but even if an object is maintaining its documented invariants, that doesn't mean its behavior in one thread will be completely unaffected by things being done to it in other threads. (For example, a ConcurrentHashMap
will never be corrupted by multiple threads operating on it concurrently, but a thread that makes multiple calls to its size()
method can get a different value each time if there's some other thread that's adding or removing elements.) So even a "thread-safe" class can sometimes be used in a non-thread-safe way (depending on the class).
Additionally, when we say that a class is "thread-safe", we assume that you're not doing anything crazy to subvert the guarantees it tries to provide. If you do, then all bets are off!

- 175,680
- 26
- 273
- 307