How to avoid needing to understand the Memory Model
suggest changeThe Memory Model is difficult to understand, and difficult to apply. It is useful if you need to reason about the correctness of multi-threaded code, but you do not want to have to do this reasoning for every multi-threaded application that you write.
If you adopt the following principles when writing concurrent code in Java, you can largely avoid the need to resort to happens-before reasoning.
- Use immutable data structures where possible. A properly implemented immutable class will be thread-safe, and will not introduce thread-safety issues when you use it with other classes.
- Understand and avoid “unsafe publication”.
- Use intrinsic locks (
synchronized) orLockobjects to synchronize access to state in mutable objects that need to be thread-safe. See note 1. - Use
Executor/ExecutorServiceor the fork/join framework rather than creating and managing threads directly. - Use the
java.util.concurrentclasses that provide locks, semaphores, latches, and barriers, instead of usingwait/notify/notifyAlldirectly. - Use the
java.util.concurrentversions of maps, sets, lists, queues, and deques rather than external synchronization of non-concurrent collections.
The general principle is to try to use Java’s built-in concurrency libraries rather than “rolling your own” concurrency. You can rely on them working, if you use them properly.
- Not all objects need to be thread-safe. For example, if an object is thread-confined (accessible to only one thread), then its thread-safety is not relevant.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents