Multithreading basics necessary knowledge points! Read the study of multi-threading multiplier

Source: Internet
Author: User
Tags closure modifier visibility volatile

Objective

Accidentally on the pigeons for a few days not updated, this week to go home. In school days to work hard one o'clock!

Only a bald head can become stronger.

Review Front:

    • Multi-threaded three minutes to enter a door!
    • Thread Source Code Analysis

The knowledge of this article is mainly referred to the first 4 chapters of the book "Java Concurrent Programming," the first 4 chapters of this book are the basis of the interpretation of concurrency. If we can understand these foundations well, then we will learn more in the future.

Of course, "Java Concurrency Programming combat" can be said to be a very classic book. I do not fully understand, in this is only a catalyst. To get a fuller understanding of what I'm talking about below, you can read the book, which is good overall.

Let's start with a preview of what the first 4 chapters of Java concurrency programming are saying:

Introduction to the 1th Chapter

    • 1.1 History of concurrency
    • 1.2 Advantages of threading
    • 1.2.1 The power of multi-processor
    • The simplicity of 1.2.2 Modeling
    • Simplified processing of 1.2.3 asynchronous events
    • 1.2.4 responds to a more responsive user interface
    • 1.3 Thread-risk
    • 1.3.1 Security Issues
    • 1.3.2 Active Issues
    • 1.3.3 Performance Issues
    • 1.4 Threads everywhere

PS: This Part I will not talk about , mainly to lead us to the next point of knowledge, interested students can turn to read the original book ~

2nd Chapter Thread Safety

    • 2.1 What is thread safety
    • 2.2 atomicity
    • 2.2.1 Race condition
    • 2.2.2 Example: Race condition in deferred initialization
    • 2.2.3 Compound operation
    • 2.3 Plus lock mechanism
    • 2.3.1 Built-in lock
    • 2.3.2 Re-entry
    • 2.4 Using locks to protect status
    • 2.5 Activity and performance

Chapter 3rd Sharing of objects

    • 3.1 Visibility
    • 3.1.1 Failure data
    • 3.1.2 64-bit operation for non-atomic
    • 3.1.3 Locking and visibility
    • 3.1.4 Volatile variable
    • 3.2 Release and escape
    • 3.3 Thread closure
    • 3.3.1 Ad-hoc Thread closure
    • 3.3.2 Stack Closure
    • 3.3.3 Threadlocal Class
    • 3.4 invariance
    • 3.4.1 Final Domain
    • 3.4.2 Example: Using volatile types to publish immutable objects
    • 3.5 Security release
    • 3.5.1 Incorrect publication: The correct object is destroyed
    • 3.5.2 immutable objects and initialization security
    • Common patterns for 3.5.3 security releases
    • 3.5.4 Facts Non-mutable objects
    • 3.5.5 mutable objects
    • 3.5.6 Sharing objects securely

Chapter 4th the combination of objects

    • 4.1 Designing Thread-safe classes
    • 4.1.1 Collecting synchronization requirements
    • 4.1.2 Dependent State operation
    • Ownership of the 4.1.3 State
    • 4.2 Instance Closure
    • 4.2.1 Java Monitor mode
    • 4.2.2 Example: Vehicle tracking
    • 4.3 Thread-Safe delegation
    • 4.3.1 Example: Consignment-based vehicle tracker
    • 4.3.2 Independent State variables
    • 4.3.3 when a delegate fails
    • 4.3.4 Publishing the underlying state variable
    • 4.3.5 Example: Vehicle tracker for release status
    • 4.4 Adding functionality to existing thread-safe classes
    • 4.4.1 Client lock mechanism
    • 4.4.2 Combination
    • 4.5 Document the synchronization policy

So let's start with the next thing.

I. Problems encountered with multithreading 1.1 thread safety issues

In the previous article has explained the thread "multithreading three minutes can enter a door!" "Multithreading is primarily designed to improve the usage of our applications . But at the same time, this will bring us a lot of security problems !

There is no problem if we execute the code in a single thread in a "sequential" (serial-to-exclusive) manner. But in the multi-threaded environment (parallel), if not well designed and controlled, it will bring us a lot of unexpected situation, that is, thread security problems

Because threads are executed alternately in a multithreaded environment, they typically use multiple threads to execute the same code . If there is a shared variable in the same code, or some combination , the correct result we want is very easy to do.

A simple example:

    • The following program runs in a single thread and is no problem .
publicclassextendsimplements Servlet {    privatelong0;    publiclonggetCount() {        return count;    }    publicvoidservicethrows ServletException, IOException {        ++count;        // To something else...    }}

But in the multi-threaded environment to run up, its count value calculation is wrong!

First, it shares the variable of count, and secondly it ++count; 's a combined operation (note that it's not atomic )

    • ++countThe actual operation is this:
      • Read Count value
      • The value +1
      • Writes the result of the calculation to count

As a result, multithreaded execution is likely to be the case:

    • When thread a reads the value of Count to 8, thread B also goes in this method, and the value of read to count is 8.
    • They both add 1 to the value.
    • Writes the result of the calculation to count. However, the result that is written to count is 9
    • That is: Two threads have come in, but the correct result is that it should return to ten, and it returns 9, which is not normal!

If the class always behaves correctly when multiple threads access a class, then this class is thread safe!

There is a principle that the JDK can be used using the thread-safe mechanism provided by the JDK .

Of course, this part is actually the most important part of our learning multi-threading , here I will not say in detail. Here is a general overview, these knowledge points in the back of the study will encounter ~ ~ ~

1.3 Performance issues

Using multithreading our goal is to improve application usage, but it doesn't necessarily improve efficiency if multithreaded code is not well designed . instead, it lowers efficiency and can even cause deadlocks !

Just like our servlet, where a Servlet object can handle multiple requests, theservlet is obviously a natural support for multithreading .

Again, in the following example:

publicclassextendsimplements Servlet {    privatelong0;    publiclonggetCount() {        return count;    }    publicvoidservicethrows ServletException, IOException {        ++count;        // To something else...    }}

From the above we have said that the above class is thread insecure. The simplest way: if we add the built-in lock synchronized provided by the JDK to the service method, then we can implement thread safety.

publicclassextendsimplements Servlet {    privatelong0;    publiclonggetCount() {        return count;    }    publicvoidsynchronizedservicethrows ServletException, IOException {        ++count;        // To something else...    }}

Although thread-safe is implemented, this can cause serious performance problems :

    • Each request has to wait for The service method of the previous request to be processed before the corresponding operation can be completed

This leads to: we complete a small function, the purpose of using multi-threaded is to improve efficiency, but now not grasp properly, but bring serious performance problems !

In the use of multithreading: more serious when there is a deadlock (the program will not be stuck).

These are the next things we want to learn: learning which synchronization mechanism to use for thread safety, and performance is improved rather than reduced by ~

Second, the release and escape of the object

The book is defined in such a way as to publish and escape:

Publish (publish) enables an object to be used in code outside the current scope

Escape (Escape) when an object that should not be published is published

Common escapes are in the following ways:

    • Static Domain Escape
    • Public-Modified Get method
    • Method parameter Passing
    • An implicit this

Static domain escape:

Public to modify the Get method:

Method parameter Passing I'm not going to show it anymore, because passing the object over to another method is already escaping.

Here's a look at the book giving an example of this escape :

escaping is the place where the object should not be published, and the object is published . Cause our data to leak out, which creates a security hazard ! Is it easy to understand that you lost it?

2.1 Secure Publishing objects

There are a couple of escaping scenarios, and we'll talk about how to safely publish objects .

There are several common ways to safely publish objects:

    • initialize directly in the static domain : public static Person = new Person() ;
      • Static initialization is performed by the JVM at the initialization stage of the class, andthere is a synchronization mechanism inside the JVM , so that we can safely publish the object
    • The corresponding reference is saved to the volatile or atomicreferance reference
      • Guarantees the visibility and atomicity of the object's reference
    • Modified by final
      • The object is immutable, then the thread must be secure, so it is safe to publish ~
    • protected by locks
      • When you publish and use it, you need to lock it to ensure that the object does not escape.
Third, solve the problem of multithreading encountered

From the above we can see that the use of multithreading will make our system very complicated. Is that we need to deal with a lot of things, in order to prevent multithreading to bring us security and performance problems ~

Here's a brief summary of what we need to know to solve the problem of multithreading.

3.1 A brief description of ways to address thread safety

Use multithreading to ensure that our threads are safe , this is the most important place!

In Java, we generally have the following methods to implement thread safety issues:

    • Stateless ( no shared variable )
    • Use final to make the reference variable immutable (if the object reference also refers to other objects, it needs to be unlocked whether it is published or used)
    • Locking (built-in lock, display lock Lock)
    • Thread safety using the classes provided by the JDK (this section has a lot of classes)
      • Atomicity (such as the above count++ operation, you can use Atomiclong to achieve atomicity, then the increase in time will not travel wrong!) )
      • Containers (Concurrenthashmap, etc...)
      • ......
    • ... Wait a minute
3.2 Atomicity and visibility

What is atomicity? What is visibility? At the outset, I was in concurrenthashmap based on the JDK1.8 source code analysis has simply said a bit. Students who do not know can go in and see.

3.2.1 Atomic Nature

Most of the time in multi-threading is because an operation is not atomic, causing data confusion to occur. If the data of the operation is atomic, then the problem of thread safety can be largely avoided!

    • count++, first read, then self-increment, and then assign value. if the operation is atomic, then it can be said that the thread is safe (because there is no intermediate three parts, one step "atomicity"~

atomicity is the act of doing an operation that is indivisible ,
-for example, the above count++ operation, it is not an atomic operation, it is divided into three steps to achieve this operation ~
- Atomic package in JDK provides us with atomic operation ~

Some people have made it into a table to classify, let's take a look at:

The use of these class-related operations can also go into his blog to see:

    • 51553338
3.2.2 Visibility

For Visibility , Java provides a keyword: volatile gives us the use of ~

    • We can simply assume that volatile is a lightweight synchronization mechanism

Volatile Classic Summary:volatile is only used to ensure that the variable is visible to all threads, but does not guarantee atomicity

Let's take it apart to explain:

    • Ensure that the variable is visible to all threads
      • In a multithreaded environment: when this variable is modified, all threads will know that the variable has been modified , known as the "visibility"
    • No guarantee of atomicity
      • Modifying a variable (Assignment) is essentially a matter of several steps in the JVM, which is unsafe in these steps (from loading variables to modifications) .

Variables with volatile modifiers guarantee three points :

    • Once you have finished writing, any thread accessing this field will get the most recent value
    • Before you write, it is guaranteed that all previous events have occurred and that any updated data values are visible because the memory barrier flushes the previous write values to the cache.
    • volatile to prevent reordering (reordering refers to the execution of the program, the CPU, the compiler may make some adjustments to the order of execution , resulting in the order of execution is not from the top down.) And there are some unexpected effects). If volatile is declared, then the CPU and compiler will know that the variable is shared and will not be cached in registers or other invisible places.

In general,volatile is mostly used for flag positions (judging operations), and the following conditions should be used to use volatile modifier variables:

    • do not depend on the current value of a variable when modifying a variable (because volatile is not guaranteed to be atomic)
    • the variable is not included in the invariant condition (the variable is variable)
    • no lock required when accessing variables (There is no need for locking to use the lightweight synchronization mechanism of volatile)

Resources:

    • Http://www.cnblogs.com/Mainz/p/3556430.html
    • Https://www.cnblogs.com/Mainz/p/3546347.html
    • Http://www.dataguru.cn/java-865024-1-1.html
3.3 Thread closure

In a multithreaded environment, if we don't use member variables (no sharing of data), then there's no thread-safe problem.

We use the familiar servlet to give examples, write so many servlets, you have seen we said to lock it?? All of our data is operated on the method (stack closed), each of which has its own variables and does not interfere with each other!

On the method, as long as we guarantee not to publish the object on the stack (method) (the scope of each variable is only stuck on the current method), then our thread is safe

There is another way of thread closure, which I wrote before: Threadlocal is so simple.

Using this class of APIs ensures that each thread has its own one variable . (Read the above article for details) ~

3.4 invariance

Immutable objects must be thread-safe.

The variables we shared above are mutable and are subject to thread-safety problems because they are mutable. If the state is immutable , then access to any number of threads is no problem !

Java provides the final modifier for us to use, the final figure we may have seen more, but it is worth explaining that:

    • Final is simply not able to modify the reference to the variable, but the data inside the reference can be changed!

It was as if the following hashmap, with final decoration. However, it only guarantees that the object reference hashMap变量 is immutable, but the data inside the HashMap is mutable, that is to say: you can add,remove and so on to the collection ~ ~ ~

    • So, just to be able to explain that HashMap is an immutable object reference
  finalnew HashMap<>();

Immutable Object references need to be locked at the time of use

    • Or the person is also designed to be a thread-safe class ~
    • Because the internal state is mutable, unlocked, or the person is not a thread-safe class, the operation is dangerous !

To design an object as an immutable object, the following three conditions are met:

    • The state cannot be modified after the object is created
    • All fields of the object are final decorated
    • object is created correctly. (no this reference escapes)

String in our learning process we know that it is an immutable object , but it does not follow the 2nd (all fields of the object are final decorated), because the JVM is internally optimized. But if we are to design an immutable object ourselves, we need to meet three conditions.

3.5 Thread Safety Delegation

Many times we want to implement thread safety does not necessarily need to lock themselves, to design .

We can use the JDK to provide us with the object to complete the thread-safe design:

A lot of "tools" for us to use, these will be introduced in the future study ~ ~ Here is not introduced

Iv. final

The correct use of multithreading can improve the efficiency of our applications while giving us a lot of problems that we need to be aware of before we use multithreading.

Whether it is immutability, visibility, atomicity, thread closure, delegation, these are a means of implementing thread safety. To use these tools wisely, our program can be more robust!

What can be found is that it says in many places: lock . But I did not introduce it, because I intend to stay in the next post to write, please expect ~ ~ ~

The first 4 chapters of the book took 65 pages to explain, and I only used an article to summarize, this is far from enough, want to continue in-depth students can go to read books ~

Before learning the operating system in accordance with the "Computer operating system-Tang Xiaodan" This book also made a little note, are relatively superficial knowledge points . It might be helpful to everyone.

    • Operating system The first "introduction"
    • Operating system second "process management"
    • Operating system The third "thread"
    • Operating system fourth "processor scheduling"
    • Fifth chapter "Deadlock" of the operating system
    • Sixth chapter "Memory Management" of the operating system
    • Operating system Seventh "device Management"

Resources:

    • "Java Core technology Volume One"
    • "Java Concurrency Programming"
    • "Computer operating system-Tang Xiaodan"

If the article is wrong, welcome to correct, we communicate with each other. Accustomed to looking at technical articles, want to get more Java resources of students, can pay attention to the public number: Java3y. For everyone's convenience, just new QQ Group: 742919422, we can also go to exchange. Thanks for the support! I hope to introduce more to other needy friends.

Directory navigation for articles :

    • Https://zhongfucheng.bitcron.com/post/shou-ji/wen-zhang-dao-hang

Multithreading basics necessary knowledge points! Read the study of multi-threading multiplier

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.