Concurrent
66. Synchronizing access to shared mutable data
The keyword synchronized can guarantee that only one thread can execute a method, or a block of code, at the same time.
If there is no synchronization, the change of one thread cannot be seen by other threads. Synchronization not only prevents a thread from seeing an object in an inconsistent state, it also guarantees that every thread that enters the synchronization method or synchronizes the code block sees all the modifications that were previously protected by a lock.
The Java language Specification guarantees that reading and writing a variable is atomic unless the variable is of type long or double. means reading a variable of a non-long or double type, which guarantees that the returned value is stored in the variable by a thread, even if multiple threads modify the variable concurrently without synchronization.
The memory model in the Java language Specification, which specifies when and how changes made by one thread become visible to other threads.
The Valatile modifier does not perform mutually exclusive access, but it guarantees that any thread reading the domain will see the value that was recently written.
The increment operator (+ +) is not atomic. Divide two operations, read the value first, and then write a new value.
You can add the synchronized modifier. You can then remove the volatile modifier.
Best practice is to use class Atimiclong to perform better than synchronized
When multiple threads share variable data, each thread that reads or writes data must perform synchronization.
Failure to share volatile data synchronously can cause program activity failures and security failures. Such failures are most difficult to debug.
If the interaction between threads does not require mutual exclusion, the volatile master is an acceptable form of synchronization, but it may take some skill to use it correctly.
Effective Java tenth concurrency simultaneous access to shared variable data reading notes