Simplest and understandable example of volatile keyword in Java

后端 未结 12 874
梦谈多话
梦谈多话 2020-11-28 19:43

I\'m reading about volatile keyword in Java and completely understand the theory part of it.

But, what I\'m searching for is, a good case example, which sho

12条回答
  •  猫巷女王i
    2020-11-28 20:23

    Variable Volatile: Volatile Keyword is applicable to variables. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.

    Access_Modifier volatile DataType Variable_Name;
    

    Volatile Field: An indication to the VM that multiple threads may try to access/update the field's value at the same time. To a special kind of instance variables which has to shared among all the threads with Modified value. Similar to Static(Class) variable, Only one copy of volatile value is cached in main memory, So that before doing any ALU Operations each thread has to read the updated value from Main memory after ALU operation it has to write to main memory direclty. (A write to a volatile variable v synchronizes-with all subsequent reads of v by any thread) This means that changes to a volatile variable are always visible to other threads.

    Here to a nonvoltaile variable if Thread t1 changes the value in t1's cache, Thread t2 can't access the changed value untill t1 writes, t2 read from main memory for the most recent modified value, which may lead to Data-Inconsistancy.

    volatile cannot be cached - assembler

        +--------------+--------+-------------------------------------+
        |  Flag Name   |  Value | Interpretation                      |
        +--------------+--------+-------------------------------------+
        | ACC_VOLATILE | 0x0040 | Declared volatile; cannot be cached.|
        +--------------+--------+-------------------------------------+
        |ACC_TRANSIENT | 0x0080 | Declared transient; not written or  |
        |              |        | read by a persistent object manager.|
        +--------------+--------+-------------------------------------+
    

    Shared Variables: Memory that can be shared between threads is called shared memory or heap memory. All instance fields, static fields, and array elements are stored in heap memory.

    Synchronization: synchronized is applicable to methods, blocks. allows to execute only 1-thread at a time on object. If t1 takes control, then remaining threads has to wait untill it release the control.

    Example:

    public class VolatileTest implements Runnable {
    
        private static final int MegaBytes = 10241024;
    
        private static final Object counterLock = new Object();
        private static int counter = 0;
        private static volatile int counter1 = 0;
    
        private volatile int counter2 = 0;
        private int counter3 = 0;
    
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                concurrentMethodWrong();
            }
    
        }
    
        void addInstanceVolatile() {
            synchronized (counterLock) {
                counter2 = counter2 + 1;
                System.out.println( Thread.currentThread().getName() +"\t\t « InstanceVolatile :: "+ counter2);
            }
        }
    
        public void concurrentMethodWrong() {
            counter = counter + 1;
            System.out.println( Thread.currentThread().getName() +" « Static :: "+ counter);
            sleepThread( 1/4 );
    
            counter1 = counter1 + 1;
            System.out.println( Thread.currentThread().getName() +"\t « StaticVolatile :: "+ counter1);
            sleepThread( 1/4 );
    
            addInstanceVolatile();
            sleepThread( 1/4 );
    
            counter3 = counter3 + 1;
            sleepThread( 1/4 );
            System.out.println( Thread.currentThread().getName() +"\t\t\t\t\t « Instance :: "+ counter3);
        }
        public static void main(String[] args) throws InterruptedException {
            Runtime runtime = Runtime.getRuntime();
    
            int availableProcessors = runtime.availableProcessors();
            System.out.println("availableProcessors :: "+availableProcessors);
            System.out.println("MAX JVM will attempt to use : "+ runtime.maxMemory() / MegaBytes );
            System.out.println("JVM totalMemory also equals to initial heap size of JVM : "+ runtime.totalMemory() / MegaBytes );
            System.out.println("Returns the amount of free memory in the JVM : "+ untime.freeMemory() / MegaBytes );
            System.out.println(" ===== ----- ===== ");
    
            VolatileTest volatileTest = new VolatileTest();
            Thread t1 = new Thread( volatileTest );
            t1.start();
    
            Thread t2 = new Thread( volatileTest );
            t2.start();
    
            Thread t3 = new Thread( volatileTest );
            t3.start();
    
            Thread t4 = new Thread( volatileTest );
            t4.start();
    
            Thread.sleep( 10 );;
    
            Thread optimizeation = new Thread() {
                @Override public void run() {
                    System.out.println("Thread Start.");
    
                    Integer appendingVal = volatileTest.counter2 + volatileTest.counter2 + volatileTest.counter2;
    
                    System.out.println("End of Thread." + appendingVal);
                }
            };
            optimizeation.start();
        }
    
        public void sleepThread( long sec ) {
            try {
                Thread.sleep( sec * 1000 );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    Static[Class Field] vs Volatile[Instance Field] - Both are not cached by threads

    • Static fields are common to all threads and get stored in Method Area. Static with volatile no use. Static field cant be serialized.

    • Volatile mainly used with instance variable which get stored in heap area. The main use of volatile is to maintain updated value over all the Threads. instance volatile field can be Serialized.

    @see

    • Volatile Vs Static in java
    • System with multiple cores sharing an L2 cache
    • JVM memory model

提交回复
热议问题