Java concurrent programming: core theory and java concurrency core Theory

Source: Internet
Author: User

Java concurrent programming: core theory and java concurrency core Theory

Concurrent Programming is one of the most important skills and the most difficult skills for Java programmers. It requires programmers to have a deep understanding of the underlying operating principles of computers, while requiring programmers to have clear logic and meticulous thinking so that they can write efficient, secure, and reliable multi-thread concurrent programs. This series will begin with the nature of thread coordination methods (wait, notify, notifyAll), Synchronized, and Volatile. It will explain in detail the various concurrency tools and underlying implementation mechanisms that JDK provides for us. On this basis, we will further analyze the java. util. concurrent package tool class, including its usage, implementation source code, and the principles behind it. This is the first article in this series and the core theoretical part of this series. later articles will analyze and explain it on this basis.

I. Sharing

Data sharing is one of the main reasons for thread security. If all the data is valid only within the thread, there will be no thread security issues, which is one of the main reasons we often do not need to consider thread security during programming. However, in multi-threaded programming, data sharing is inevitable. The most typical scenario is the data in the database. To ensure data consistency, we usually need to share the data in the same database, even if the master and slave databases access the same data, master/Slave only copies of the same data for access efficiency and data security. Now, we use a simple example to demonstrate the problems caused by data sharing under multiple threads:

Code snippet 1:

Package com. paddx. test. concurrent; public class upload data {public static int count = 0; public static void main (String [] args) {final upload data = new upload data (); for (int I = 0; I <10; I ++) {new Thread (new Runnable () {@ Override public void run () {try {// pause for 1 millisecond upon entry, increase the chance of concurrent problems. sleep (1);} catch (InterruptedException e) {e. printStackTrace () ;}for (int j = 0; j <100; j ++) {data. addCount ();} System. out. print (count + "");}}). start ();} try {// The main program is suspended for 3 seconds to ensure that the preceding program is executed successfully. sleep (3000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("count =" + count);} public void addCount () {count ++ ;}}

The purpose of the above Code is to add one operation to count and execute it for 1000 times. However, it is implemented through 10 threads. Each thread executes 100 times. Normally, it should output 1000. However, if you run the above program, you will find that the result is not like this. The following is an execution result (the results of each operation are not necessarily the same, and sometimes the correct results may be obtained ):

Ii. Mutual Exclusion

Resource mutual exclusion means that only one visitor can access the resource at the same time, which is unique and exclusive. We usually allow multiple threads to read data at the same time, but only one thread can write data at the same time. Therefore, we usually divide locks into shared locks and exclusive locks, also known as read locks and write locks. If resources are not mutually exclusive, we do not need to worry about thread security even if resources are shared. For example, for immutable data sharing, all threads can only perform read operations on it, so thread security issues are not considered. However, write operations on shared data generally require mutual exclusion. In the above example, data modification is caused by the absence of mutual exclusion. Java provides multiple mechanisms to ensure mutual exclusion. The simplest way is to use Synchronized. Now we add Synchronized to the above program and execute it again:

Code Segment 2:

Package com. paddx. test. concurrent; public class upload data {public static int count = 0; public static void main (String [] args) {final upload data = new upload data (); for (int I = 0; I <10; I ++) {new Thread (new Runnable () {@ Override public void run () {try {// pause for 1 millisecond upon entry, increase the chance of concurrent problems. sleep (1);} catch (InterruptedException e) {e. printStackTrace () ;}for (int j = 0; j <100; j ++) {data. addCount ();} System. out. print (count + "");}}). start ();} try {// The main program is suspended for 3 seconds to ensure that the preceding program is executed successfully. sleep (3000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("count =" + count);}/*** added the synchronized keyword */public synchronized void addCount () {count ++ ;}}

After executing the above Code, we will find that the final result returned is 1000 no matter how many times it is executed.

Iii. atomicity

Atomicity means that operations on data are an independent and inseparable whole. In other words, an operation is a continuous and uninterrupted process, and the data is modified by other threads when half of the data is not executed. The simplest way to ensure atomicity is operating system commands. That is to say, if an operation corresponds to an operating system command, it will certainly ensure atomicity. However, many operations cannot be completed using one command. For example, for long-type operations, many systems need to be divided into multiple commands to perform high and low Operations respectively. For example, we often use integer I ++ operations, which need to be divided into three steps: (1) reading the value of integer I; (2) adding one to I; (3) write the result back to the memory. This process may occur in multiple threads as follows:

This is why the execution result of code snippet 1 is incorrect. For this combination operation, the most common way to ensure atomicity is locking. For example, Synchronized or Lock in Java can be implemented. Code Segment 2 is implemented through Synchronized. In addition to the lock, CAS (Compare And Swap) is another method. before modifying the data, Compare whether the data is consistent with the previously read value. If the data is consistent, modify the data, if they are inconsistent, execute again. This is also the implementation principle of optimistic locks. However, CAS is not necessarily valid in some scenarios. For example, if another thread modifies a value first and then changes it back to the original value, CAS cannot be judged.

Iv. Visibility

To understand the visibility, you must first understand the JVM memory model. The JVM memory model is similar to that of the operating system ,:

Package com. paddx. test. concurrent; public class VisibilityTest {private static boolean ready; private static int number; private static class ReaderThread extends Thread {public void run () {try {Thread. sleep (10);} catch (InterruptedException e) {e. printStackTrace ();} if (! Ready) {System. out. println (ready);} System. out. println (number) ;}} private static class WriterThread extends Thread {public void run () {try {Thread. sleep (10);} catch (InterruptedException e) {e. printStackTrace () ;}number = 100; ready = true ;}} public static void main (String [] args) {new WriterThread (). start (); new ReaderThread (). start ();}}

Intuitively, this program should only output 100, and the value of ready will not be printed. In fact, if you execute the above Code multiple times, there may be a variety of different results. The following is the result of one or two running operations:

V. Sequence

To improve performance, the compiler and processor may re-sort the commands. There are three types of sorting:

(1) reordering optimized by the compiler. The compiler can reschedule the statement execution sequence without changing the semantics of a Single-threaded program.

(2) command-level parallel re-sorting. Modern processors use the Instruction-Level Parallelism (ILP) technology to execute multiple commands in an overlapping manner. If there is no data dependency, the processor can change the execution sequence of the statements corresponding to the machine commands.
(3) memory system re-sorting. Because the processor uses cache and read/write buffer, loading and storage operations may appear to be executed in disorder.

For details, refer to the reordering problem in JSR 133:

  

(1) (2)

First look at the (1) Source Code section. From the source code, either command 1 is executed first or command 3 is executed first. If Instruction 1 is executed first, r2 should not be able to see the value written in instruction 4. If command 3 is executed first, r1 should not be able to see the value written in command 2. However, the running results may contain r2 = 2, r1 = 1, which is the result of "re-sorting. (2) It is a possible legal compilation result. After compilation, the order of commands 1 and 2 may be changed. Therefore, the result of r2 = 2, r1 = 1 appears. In Java, Synchronized or Volatile can also be used to ensure sequence.

Summary

This article explains the theoretical basis of Java concurrent programming. Some things will be discussed in more detail in the subsequent analysis, such as visibility and sequence. Subsequent articles will be discussed based on the content of this chapter. If you can understand the above content well, I believe that both the article on understanding other concurrent programming and the work on concurrent programming can be of great help to everyone.

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.