Learning java multithreading with examples 5-getting started with volatile Variables
The synchronization mechanism can ensure atomic operations and memory visibility, but the access performance of the synchronization mechanism to variables is an issue that we have to consider. java provides a weak synchronization mechanism, volatile variable.
The principle is roughly like this. When the variable is declared as volatile type, the compiler and runtime will notice that this variable is shared, therefore, operations on variables are not reordered together with other memory operations. Volatile variables are not cached in registers or invisible to other processors. Therefore, when reading volatile variables, the latest written values are always returned. (Refer to java concurrent programming practices)
Let's look at an example:
Package com. home. thread;/*** @ author gaoxu **/public class ThreadStart {private static class ReaderThread extends Thread {public void run () {SafeThread. setNumber (1) ;}} private static class ReaderThread1 extends Thread {public void run () {long start = System. currentTimeMillis (); System. out. println ("=" + SafeThread. getNumber (); long endTime = System. currentTimeMillis ()-start; System. out. println ("time used:" + endTime) ;}} public static void main (String [] para) {new ReaderThread (). start (); new ReaderThread1 (). start ();}}
package com.home.thread;import java.util.concurrent.atomic.AtomicInteger;/** * @author gaoxu * */public class SafeThread {volatile static int number;public static int getNumber() {return number;}public static void setNumber(int number) {SafeThread.number = number;}}
The running result of this Code is 1. That is to say, getNumber ensures that the latest memory value of the number variable is obtained, which is the credit of volatile, we can imagine the access to volatile variables as a set and get operation of synchronized (although synchronization is far more visible than volatile memory). volatile seems convenient to use, however, its use is limited.
The use of volatile variables can only ensure the memory visibility of variables, but cannot guarantee the atomicity of variables. Therefore, the use of volatile variables has the following conditions:
Write operations on variables do not depend on the current value of the variable, or you can ensure that only one thread updates the value of the variable.
This variable is not included in the constant condition with other state variables.
You do not need to lock variables.
We can see that the example of the above Code fully meets these conditions, so this example can use volatile.
In addition, we also added the code for testing time in the Code:
Run 10 times in each mode.
The conclusion is that the volatile variable is 1 millisecond faster than the synchronization average. (Low accuracy)
Zookeeper