Volatile, synchronized in Java

Source: Internet
Author: User
Tags visibility volatile

First, add the concept: visibility, atomicity, and ordering in the Java memory model.

Visibility of:

Visibility is a complex property, because errors in visibility always violate our intuition. In general, we cannot ensure that threads that perform read operations can see the values written by other threads in a timely fashion, sometimes even impossible. In order to ensure the visibility of memory write operations between multiple threads, the synchronization mechanism must be used.

  visibility refers to the visibility between threads, and the state of one thread modification is visible to another thread. that is, the result of a thread modification. Another thread can see it right away. For example: variables modified with volatile will have visibility. Volatile-modified variables do not allow the thread to cache and reorder internally, that is, to modify memory directly. So it is visible to other threads. But there is a problem to be aware of, and volatile can only make it visible to the content he modifies, but it does not guarantee that it is atomic. For example, volatile int a = 0, then there is an operation a++, this variable a has visibility, but a++ is still a non-atomic operation, that is, the operation also has a thread safety problem.

Volatile, synchronized, and final implementation visibility in Java.

Atomic nature:

  atoms are the smallest units in the world and are indivisible. such as a=0; (a non-long and double type) This operation is indivisible, then we say this operation is atomic operation. Another example: a++; This operation is actually a = a + 1; is divisible, so he is not an atomic operation. There is a thread-safety problem with non-atomic operations, and we need to use synchronous technology (sychronized) to turn it into an atomic operation. An operation is an atomic operation, so we call it atomic. The Java concurrent package provides some atomic classes, and we can read the API to understand the use of these atomic classes. For example: Atomicinteger, Atomiclong, atomicreference and so on.

Synchronized in Java and operation in lock, unlock guarantees atomicity.

Order:

  The Java language provides the volatile and synchronized two keywords to ensure the ordering of operations between threads, because it contains the semantics of "no order reordering" itself, and synchronized is made up of " A variable that allows only one thread to lock on it at the same time "this rule determines that two synchronization blocks holding the same object lock can only be executed serially.

 Public classVisibilitytestextendsThread {Private  Booleanstop;  Public voidrun () {inti = 0;  while(!stop) {i++; } System.out.println ("Finish loop,i=" +i); }     Public voidStoPit () {Stop=true; }     Public BooleanGetstop () {returnstop; }     Public Static voidMain (string[] args)throwsException {visibilitytest v=Newvisibilitytest ();        V.start (); Thread.Sleep (1000);        V.stopit (); Thread.Sleep (2000); System.out.println ("Finish Main");    System.out.println (V.getstop ()); }}
Second, the volatile principle

The Java language provides a slightly weaker synchronization mechanism, the volatile variable, that is used to ensure that updates to variables are notified to other threads. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached in registers or in places that are not visible to other processors, so the most recent write value is always returned when reading a variable of type volatile.

The volatile variable is a more lightweight synchronization mechanism than the Sychronized keyword, because it does not perform a lock operation when accessing a volatile variable, and therefore does not cause the execution thread to block.

When reading and writing non-volatile variables, each thread first copies variables from memory to the CPU cache. If the computer has multiple CPUs, each thread may be processed on a different CPU, which means that each thread can be copied to a different CPU cache.

While declaring variables to be volatile, the JVM guarantees that each read variable is read from memory, skipping the CPU cache step.

When a variable is defined as volatile, there are two characteristics:

1. Ensure that this variable is visible to all threads, where the "visibility", as described at the beginning of this article, when a thread modifies the value of this variable, volatile guarantees that the new value is immediately synchronized to the main memory and flushed from the main memory immediately before each use. But ordinary variables do not do this, the value of the normal variable between the thread pass through the main memory (see: Java memory Model) to complete.

2. Prohibit command reordering optimization. A variable with a volatile modifier, after which the assignment performs a "Load Addl $0x0, (%ESP)" operation, which is equivalent to a memory barrier (the command reordering cannot reorder the subsequent instructions to the memory barrier), Memory barriers are not required when only one CPU accesses memory; (What is command reordering: refers to the CPU used to allow multiple instructions not in accordance with the program specified in the order of development to each corresponding Circuit unit processing).

Volatile, synchronized in Java

Related Article

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.