Java Thread-volatile

Source: Internet
Author: User

Foreword-strenuously forget to eat, music to forget excellent, do not know the old will.

Description: In Java, a variable modified by the variables, the thread will read the variable at each time the variable is the most value [Note: Do not be misled by this word. Explain in detail later].volatile is easy to be [Misuse], used for [Atomic NatureOperation

Explanation: In the Java Virtual machine running mechanism, the Java thread to run the program, in order to ensure the efficiency of the program run, each thread runs, the virtual opportunity to separate a temporary memory area for this thread, we can call [current thread-specific memory]

The thread will load the variables needed to run the process into the [current thread-specific memory], (for example, thread A needs to perform an operation on the + + of variable A, when online preempted, the variable A is first added to its own [current thread-specific memory], when the thread

When the execution is complete, the current is saved in the [current thread-specific memory], updated to the [Raw MemoryOf.

Problem: If there are two threadsAAndB, at the same time the variable upate operation, then in two thread execution, there may be a situation, two threads into the program, all in their own [current thread-specific memory], the original value of the variable is saved. Then two threads execute

When finished, the update operation of the last thread that executes overwrites the update operation performed by the first thread.----------------The program is out of sync (the bank is taking money to save.)


Solution Ideas
1. At the same time, only one program to perform the update operation----------inefficient-------synchronized
    
2. When performing the updtae operation, let the thread not from the [current thread-specific memory], instead of reading the variable directly from memory--------more efficient------- volatile


Java Thread-volatile

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.