Java Concurrency principle Talk

Source: Internet
Author: User

Processes, threads, and concurrent entities

One of the most important concepts in operating system principles is the process. A process is the concept of program dynamics, which is used to represent a set of data structures that a program executes . This set of data structures records the instructions loaded into the in-memory address, open files, thread information, shared memory, and so on.

Each process can have multiple threads. It is also a set of data structures including: The next command to execute, registers, stacks, states, and so on. A picture to show

Draw 4 Threads (threads 2, 3, 4 and 1 are the same, not full), and if the program does not start any threads, it will actually use the thread-the main thread (threads 1 in the figure). so the last CPU thread is consumed instead of the process

Actually in Linux (I really don't know windows, I guess it should be) the process and thread are the same data structure--task_struct, for the kernel (kernel) there is no process and thread differences, only the process--kernel called the task. So in Linux, processes and threads do not have a parent-child relationship but a parallel structure , which means that the data structure of the process is populated with a few more, including open files, shared memory, this is called the main thread, the data structure of other threads is empty, and there is a "parent process" Pointer, pointing to the main thread.

To understand this, we know that the smallest object of operating system scheduling is actually a thread , but the name is task, and the textbook is called process .... Is it a bit confusing? So we're introducing a new term-- concurrent entities . The smallest unit of all CPU scheduling we collectively refer to the concurrent entity, whether it is a process or a thread, or something else, "freak." (Yes, I'll introduce these freaks next time.) )

Why should threads

The man who bravely raised this question was to be praised, and he risked being mercilessly ridiculed to raise an idiotic question. (I don't think the person who answers this question is the real idiot) answer this question to answer another basic question-why do you want to

Let's imagine a Web server that might be the following code

while (true) {     request = Next_http_request ()     request_work (Request)}

The program loops through the new request (Next_http_request), executes the request (Request_work), and then proceeds to the next loop. Request_work reads the file from the hard disk and then sends it to the client as an HTTP response, while the hard disk I/O is a blocking operation, which means that request_work will wait until the data is read before releasing the CPU control, and then the next request has an opportunity to be executed.

This is the problem of concurrency, when the CPU is completely idle after request_work initiates the I/O, and the poor new request (next_http_request) must wait for the I/O to complete before it can gain control of the CPU. So CPU utilization is very low, and the problem of concurrency is to improve CPU utilization . Understand this and we know that concurrency only works for non-CPU-intensive programs, and if CPU utilization is high, more concurrency will only make things worse.

So why does concurrency have to be multithreaded rather than multi-process? In fact, there is no difference in the cost of process and thread creation under Linux (All task_struct), but the way that data can be shared between processes is implemented only through very complex IPC, where the code is shared and the address space is shared, so the way to share data is more efficient. (Process to consider isolation, one process has no way to directly access another process; threads do not have to be quarantined, shared memory between threads)

We modify a multithreaded version of the Web server

while (true) {     request = Next_http_request ()     request_work_in_thread (Request)}

The Request_work_in_thread method starts a thread (the work thread), and the CPU starts executing next_http_request to get the next request.

The request object is created on the main thread and can be passed directly to the work thread in Request_work_in_thread.

We increase CPU utilization so we need parallelism, we want to improve the efficiency of sharing data among concurrent entities so we chose the thread as the implementation of the Concurrency entity

Threads for Java

Okay, back to Java. Starting a thread in Java is very simple--as long as the new thread is done. The JVM will turn it into an operating system API, and if it is Linux it will generate a task_struct structure. As for the runable and the like, in fact, the final thread, even Java and the contract finally still use thread.

So at this point, we succeeded in the "operating system principle" in the process, thread and Java thread "integrated". Below begins another thing--PV operation.

Competitive conditions, critical area, PV signal volume

Well, this part of your estimate has also been returned to the teacher. It's okay, let's have a look.

As an example:

public void plus (int value) {  count = count + value;}

The logic of the program is wrong when multithreading calls plus at the same time. Count+value is not an atomic operation, it will be turned into a three CPU instruction

  • Get count of data to register (remember?) CPU Access Register only)

  • Register +value, and write back register

  • Register write back to memory

    If t1,t2 two threads execute simultaneously (count=0)

  • T1 get count of data to register

  • T1 add 10 to the value of the Register

  • T2 get count of data to register

  • T2 Add 30 to the value of the Register

  • T2 Register write back to memory (COUNT=30)

  • T1 Register write back to memory (count=10)

    We might expect 40, but the reality is 10, because T1 didn't have time to write back to memory when T2 accessed the data. When two threads access the same data, the final result depends on the order of the threads, which is called the race condition. The way to avoid competitive conditions is to "atomically" a set of actions through a critical section. In the example, it is: Count = count + value, atomically. (atomization means to be done at once; others are waiting in line.) )

Just like you go to buy coffee, the cashier is shared by all (competitive conditions), if he goes through: Ask Cup type, type, taste, charge, pay you invoice, these three processes can not be interrupted or will be messy. So everyone needs to queue up in turn. (Critical section)

How to achieve a critical section? The answer is the PV semaphore (also known as PV operation, PV primitive). It is the famous "Henan nationality" computer scientist--e.w.dijkstra Design a set of algorithms, the father this set of strict theory is the basis of modern concurrency. In a nutshell, he defines two operations.

Set a counter S

    • P S-1, if S is less than 0 hibernate otherwise continue execution

    • V s+1, if the s<=0 wakes up the wait process otherwise resumes execution

The P operation is equivalent to using a resource, and performing this operation is equivalent to: This table I contracted, you wait for me to use later. (If there is someone on the table, you can just wait.)

The V operation is equivalent to releasing the resource, and performing this operation is equivalent to: I don't need this table, who's next? Come and use it. (If there is no next person, then go straight away)

Yes, PV is the "lock". "Operating system principle" in the competition conditions, critical areas are not in reality the concept of real, only the PV operation is specifically implemented, is what we call the lock thing.

Locks in Java

All "locks" are a kind of PV operation, the difference between the lock is what is the "counter" you choose? For example, you choose the counter is the current object so the key is "synchronized" (there is also a name enhancement, naïve scientists think object-oriented lock good cow B, give it a special noun), If your counter is a value of atomic type then it may be the Atomicinteger Inc or Dec operation. This is the size of the lock , the smaller the lock, the smaller the competition conditions. Just as you buy coffee, treat the whole café as a "race condition" or a cashier as a "competitive condition", much like then the use of cafes is higher. (Some people who have bought coffee can stay at least for a while)

Summarize

I do not want to introduce the Java API in the article, and the class of the contract. (There's too much to catch a lot of these introductions.) My goal is to try to relate the things we think are the most useless to the real thing by remembering the basic course. Let everyone know-the original textbook is not deceptive, really is everywhere. Hope you read this article, can silently open the dust-laden "operating system principle." Guo Degang teacher has a saying: The actor and the actor finally competition is the Cultural Foundation, the same reason, the programmer and the programmer finally competition is the foundation , when you envy others "the ease" the easy solution to a very difficult bug; When moving your finger to solve a performance problem , and quickly grasp a new technology in a short period of time, please don't forget that he may have spent years or even decades practicing the "textbook" that you abandoned.

Finally recommended a few of the operating system book (not impetuous, every book is worth our a year slowly appreciate)

    • Modern operating system I have never seen so cow B's operating system book, not one!!! Explain the most complex truths in the most comprehensible language, the simplest examples. The most bull b is, it is very modern, very modern.

    • The mind of the computer: the philosophical principles of the operating system Heng Hengming, a professor at Shanghai Jiaotong University. The local book is characterized by thin, you like to read the book this is a good choice.

    • Linux kernel design and implementation, thin book. If you want to know more about Linux kernel you don't want to go too deep, this book is absolutely right for you

Java Concurrency principle Talk

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.