Read "The Art of Java Concurrent Programming" (i)

Source: Internet
Author: User
Tags switches volatile

Left the blog Park for a long time, since finding a job, to now basically no more blog. The habit of blogging in college is slowly disappearing and feeling ashamed. So now to start to re-cultivate this habit, regular blog is not only to learn their own knowledge of a precipitate, but also in urging themselves to continue to learn, continuous progress.

Recently in the further study of Java concurrent programming, it is self-evident that this part of the content is very important. Now take the book "The Art of concurrent programming" as the leading line and start a new round of learning.

Processes and Threads

A process is a single execution of an application on a processing machine, and the thread is the smallest basic unit of the process (personal understanding). A process can contain multiple threads.

Context Switches

As we all know, even a single-core processor supports multi-threading, the CPU allocates time to each thread through the time-slice allocation algorithm to allow threads to execute, because the time slice is very short, so at the user's point of view, it feels that multiple threads are executing simultaneously. So what is context switching? For example, when thread a executes to a step, when the CPU gives the time to thread B for execution, then when the switch is made, the system must save the state of the task that is being performed by thread A at this point, such as where it is executed, the parameters of the runtime, and so on, the next time the CPU is given to thread a for execution To correctly switch to a, and continue with the execution. So the process of a task from saving to reloading is a context switch.

Although context switching can make us feel that we can do a lot of things "at the same time," context switching also requires overhead . In the art of Java concurrent programming, the authors illustrate the serial and concurrent execution of cumulative operations, and in the results it can be seen that the different times of the cumulative operation vary depending on the result and time spent. If the cumulative operation does not exceed millions of times, the serial execution result consumes less time than parallel execution. So in some cases we need to reduce the number of context switches as much as possible, using methods such as lock-free concurrent programming, CAS algorithms, using minimal threading, and using the coprocessor. (Here I only know that there are several methods, as to how to use and in which scenario the use has not been thoroughly studied).

volatile and synchronizedvolatile

Volatile is a lightweight synchronized that guarantees the visibility of shared variables in multiprocessor development, and that volatile does not cause context switching and scheduling. Visibility means that when a thread modifies the value of a variable, another thread can read the modified value of the variable, and if a variable is modified by volatile, then the Java memory model ensures that all threads see the value of the variable as consistent.

synchronized

Each object in Java can be used as a lock, as follows:

    • For normal synchronization methods, the lock is the current instance object
    • For a static synchronization method, the lock is the class object of the current
    • For synchronous method blocks, the lock is an object configured in synchronized brackets

When a thread accesses a synchronous block of code, it must first obtain a lock, exit or throw an exception, and must release the lock. For the above three cases, the representation is:

1     /**2 * Normal synchronization method, lock is the current instance object3      */4      Public synchronized voidtest1 () {5         //TODO Something6     }7 8     /**9 * Static synchronization method, lock is the class object of the current classesTen      */ One      Public Static synchronized voidtest2 () { A         //TODO Something -     } -  the     /** - * Synchronization method block, lock is the object in synchronized brackets, here is a -      */ -      Public voidtest3 (Integer a) { +         synchronized(a) { -             //TODO Something +         } A}
Java memory model

All instance, static, and array elements in Java are stored in heap memory, and heap memory is shared between threads.

Communication between Java threads is controlled by the Java Memory Model (JMM). JMM defines the relationship between threads and main memory: Shared variables before threads are stored in main memory, each thread has a private local memory (also called working memory), and local memory stores a copy of the thread's read-write shared variables. Local memory is the abstract concept of JMM, which is not real, and includes caches, write buffers, registers, and other hardware and compiler optimizations. Java memory model structure diagram:

As you can see, thread A has to go through two steps to communicate with thread B:

    1. Thread A flushes the updated shared variables in local memory A to the main memory,
    2. Thread B Gets the shared variable after the update in main memory.

Such as:

Re-order

Reordering is a means by which compilers and processors reorder sequences of instructions in order to optimize program performance.

Data dependencies

Definition: If two operations access a variable at the same time, and one of the two operations is a write operation. There is a data dependency between the two operations at this point.

When the compiler and processor are reordered, data dependencies are observed, and the compiler and processor do not change the order in which the two operations exist that have data dependencies.

As-if-serial semantics

Semantics: No matter how reordered, the execution results of a single-threaded sequence cannot be changed. Compilers, runtime, and processors must adhere to as-if-serial semantics.

To comply with as-if-serial semantics, the compiler and processor do not reorder operations that have data dependencies, but if there is no data dependency between the operations, it is possible to reorder them. For example:

1 double pi = 3.14;  // A 2 double r = 1.0;        // B 3 double area = pi * R *r;   // C

In the above code, C relies on a,c to rely on B, so the compiler does not reorder the C before a, a, a. However, there is no dependency between A and B, so it is possible to reorder the final sequence of execution in two ways:

a->b->c;

b->a->c;

These two execution sequences have no effect on the final result.

Because of reordering, single-threaded programs do not necessarily follow the order of the program.

This article mainly describes some of the partial concept of things, first some impressions, follow-up will be in the form of code samples for a comprehensive review.

Read "The Art of Java Concurrent Programming" (i)

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.