Java multi-thread synchronized volatile Parsing
Let's talk about atomicity first: Atomic operations are called atomic operations. Before an atomic operation is completed, the thread scheduler is not interrupted. That is, one or more operations are either executed in full and the execution process is not interrupted by any factors, or they are not executed. In Java, simple operations on basic types except long and double are atomic. A simple operation is to assign values or return values. Operations such as "a = 1;" and "return a;" are atomic. However, in Java, operations like "a + = B" are not atomic, and unexpected results may occur if they are not synchronized. In our normal programming process, we often encounter such words as thread security and incomplete. I believe that many new users will have a headache at the beginning. Here is an example of an all-evil train ticket. For example, there are 10 tickets left between Hangzhou and Wuhan, and 4 ticket sites are selling tickets from Hangzhou to Wuhan. If the program is written to be thread-safe, when ticket a sells one ticket, ticket B is also selling tickets. Because ticket a has not been updated to the main memory in time after it is sold, ticket B may also sell ticket 1, which leads to the situation where two people buy a seat, this is why the thread is insecure. If the thread is secure, when ticket a is selling tickets at ticket 1, the other ticket sites can continue to sell tickets only after ticket a is sold and master memory data is updated at ticket, in addition, ticket 1 has been sold and will not be repeated. In this case, the synchronized lock mechanism is used. Synchronized is a method or block modifier. synchronized is divided into method synchronization and block synchronization. 1. synchronized instance method 1 // Add to method 2 public synchronized void function () {3 // somecode 4} the synchronization is synchronized to the object that owns the method, at the same time, only one thread can access this method (if there are several instances on one instance, they can be simultaneously executed ). 2. synchronized static method 1 public static synchronized void function () {2 // somecode3} because the static method does not belong to an object but belongs to a class, will lock the class Object of the class where this method is located. 3. synchronized block copy code 1 // synchronization Block 2 public void method1 () {3 synchronized (this) {4 // somecode 5} 6} 7 8 public void method2 (Object o) {9 synchronized (o) {10 // somecode11} 12} the copied code locks the object that calls this method (method1) or the passed object (method2). When no explicit object is used as the lock, to synchronize a piece of code, you can create a special instance variable (object) to act as a lock. Volatile is a variable modifier. A volatile type variable does not allow the thread to copy the value of the variable from the main memory to its own storage space. Therefore, a variable declared as volatile will get data synchronously in all threads. No matter you change the variable in any thread, other threads will immediately get the same result. Volatile variables have the visibility of synchronized, but do not have atomic properties. This means that the thread can automatically discover the latest value of the volatile variable. Volatile variables can be used to provide thread security, but can only be used in a very limited set of Use Cases: There is no constraint between multiple variables or between the current value of a variable and the modified value of a variable. Correct volatile modifier: a. Write operations on variables do not depend on the current value. B. The variable is not included in the variant with other variables. ========================================================== = Differences between the two ==================================== 1. volatile essentially tells the jvm that the value of the current variable in the register (Working Memory) is uncertain and needs to be read from the main memory. synchronized locks the current variable, only the current thread can access this variable, and other threads are blocked. 2. volatile can only be used at the variable level; synchronized can be used at the variable, method, and class level. 3. volatile can only realize variable modification visibility, but cannot guarantee atomicity. synchronized can ensure variable modification visibility and atomicity. 4. volatile will not cause thread blocking; synchronized may cause thread blocking. 5. Variables marked by volatile are not optimized by the compiler; variables marked by synchronized can be optimized by the compiler. Some examples: synchronized copy code 1 public class SyncTest {2 3 public static void main (String [] args) {4 Outputter outputter = new Outputter (); 5 MyThread myThread1 = new MyThread (outputter, "zhangsan"); 6 MyThread myThread2 = new MyThread (outputter, "lisi"); 7 Thread threada = new Thread (myThread1 ); 8 Thread threadb = new Thread (myThread2); 9 threada. start (); 10 threadb. start (); 11} 12 13} 14 15 class MyThr Ead implements Runnable {16 Outputter outputter; 17 String name; 18 19 public MyThread (Outputter outputter, String name) {20 this. outputter = outputter; 21 this. name = name; 22} 23 24 @ Override25 public void run () {26 outputter. output (name); 27} 28} 29 30/** 31 * when no lock is available, an uncertain value such as "zhlangisan" will be output. 32*33 * @ author lcm34 * 35 */36 class Outputter {37 public void output (String name) {38 // to ensure that the output of name is not an atomic operation, here, output each character of name 39 for (int I = 0; I <name. length (); I ++) {40 System. out. print (name. charAt (I); 41} 42} 43} 44 45/** 46 * if you want to get zhangsanlisi or lisizhangsan, you need to use synchronized. 47*48 * @ author lcm49 * 50 */51 class Outputter {52 public synchronized void output (String name) {53 // to ensure that name output is not an atomic operation, here, each character 54 for (int I = 0; I <name. length (); I ++) {55 System. out. print (name. charAt (I); 56} 57} 58} 59 60 class Outputter {61 public void output (String name) {62 // to ensure that the output of name is not an atomic operation, here, each character 63 synchronized (this) {// code block of name can also be output one by one, but it must be ensured that it is the same object 64 for (int I = 0; I <name. length (); I ++) {65 System. out. print (name. charAt (I); 66} 67} 68} 69} 70 71/** 72 * If the static code block is modified, lock the entire class Object 73*74 * @ author lcm75 * 76 */77 class Outputter {78 public synchronized static void output (String name) {79 // to ensure that name output is not an atomic operation, each character of name is output one by one (int I = 0; I <name. length (); I ++) {81 System. out. print (name. charAt (I); 82} 83} 84} the copy code volatile cannot guarantee the atomicity of variable operations 1 public class VolatileTest {2 private volatile int inc = 0; 3 4 public static void main (String [] args) {5 final VolatileTest volatileTest = new VolatileTest (); 6 for (int I = 0; I <1000; I ++) {7 new Thread () {8 @ Override 9 public void run () {10 try {11 Thread. sleep (1); 12 volatileTest. inc (); 13} catch (Exception e) {14 e. printStackTrace (); 15} 16} 17 }. start (); 18} 19 20 while (Thread. activeCount ()> 1) {21 // Ensure that all the preceding threads have completed 22 threads. yield (); 23} 24 System. out. println (volatileTest. inc); 25} 26 27 private void inc () {28 inc ++; 29} 30} copying the code running result is not 1000. The volatile keyword can ensure that there is no visibility error, however, the above program fails to guarantee atomicity. Visibility can only ensure that the latest value is read each time, but volatile cannot guarantee the atomicity of variable operations. Thread 1 performs the auto-increment operation on the variables. Thread 1 first reads the original value of the variable inc, and thread 1 is blocked. Then thread 2 performs the auto-increment operation on the variables, thread 2 also reads the original value of the variable inc, because thread 1 only reads the variable inc, but does not modify the variable, therefore, the cache row of the cache variable inc in the working memory of thread 2 will not be invalid. Therefore, thread 2 will directly read the inc value from the main memory and find that the inc value is 10, then add 1, write 11 to the working memory, and write it to the primary memory. Thread 1 then adds 1. Since the inc value has been read, note that the inc value is still 10 in the worker memory of thread 1, therefore, after thread 1 adds 1 to inc, the value of inc is 11, then 11 is written to the working memory, and finally to the main memory. After the two threads perform an auto-increment operation, inc only increases by 1. 1 // thread 12 boolean stop = false; 3 while (! Stop) {4 doSomething (); 5} 6 7 // thread 28 stop = true; copy the code above when thread 2 changes the value of the stop variable, but before writing data to the primary memory, thread 1 will keep repeating because it does not know the changes to the stop variable of thread 2. If volatile is added, the modified value is immediately written to the primary storage. When thread 2 is modified, the cache row with the cache variable stop in the working memory of thread 1 is invalid, so when thread 1 reads the stop value of the variable again, it will read it from the primary storage.