Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Thread-safety guarantees that no two threads can simultaneously access or modify some shared data. However, if two or more operations need to be performed safely, it becomes necessary to enforce atomicity. It is possible for two threads to read some shared value, independently perform operations on it and induce a race condition while storing the final result. Programmers usually assume that a thread-safe Collection does not require explicit synchronization which can be a misleading practice. It follows that a thread-safe Collection may not ensure program correctness.

Noncompliant

...

Code Example

This noncompliant example is comprised of an ArrayList collection which is non-thread-safe by default. There is, however, a way around this drawback. Most thread-unsafe classes have a synchronized thread-safe version, for example, Collections.synchronizedList is a good substitute for ArrayList and Collections.synchronizedMap is a good alternative to HashMap. One pitfall described in the coming lines, remains to be addressed even when the particular Collection offers thread-safety benefits.

...

Extension is more fragile than adding code directly to a class, because the implementation of the synchronization policy is now distributed over multiple, separately maintained source files. If the underlying class were to change its synchronization policy by choosing a different lock to guard its state variables, the subclass would subtly and silently break, because it no longer used the right lock to control concurrent access to the base class's state.

Noncompliant Code Example

Wiki Markup
This noncompliant code example defines a thread-unsafe {{KeyedCounter}} class. Even though the {{HashMap}} field is synchronized, the overall {{increment}} operation is not atomic. \[[Lee 09|AA. Java References#Lee 09]\]   

...