When is it safe to not synchronize read / write variables?
The answer to the lesson is only when you fully understand the implications for the underlying hardware, the JVM, and your application. If possible, I still recommend this approach, which starts with a lot of reading and experimenting.
In practice, you should use some commonly used patterns to minimize the number of methods or synchronized blocks in your code, without understanding all the intricacies of these patterns. This should not increase the risk for your application too much, because there are non-trivial details even around using synchronized , and if you understood all these details, you would ask another question.
However, your mileage may vary, especially if the form and implementation of the commonly used patterns mentioned are not blessed by your local concurrency guru.
Enough to clarify, give some examples
- Using stream collections, utilities, and types.
- This includes, when possible,
java.util.concurrent . - There is also a wonderful amount of additional libraries and tools for Java outside of the JDK and its ecosystem, but they are not so easily qualified as "apply now, read later."
- Using
volatile - Using secure provisioning and secure publishing
- Saving data streams locally.
- A view of hassle-free and surprisingly often applicable.
source share