Concurrency and multithreading-talk about the long-time job interview with less volatile

Source: Internet
Author: User
Tags thread class volatile

When it comes to volatile, some of the students who have attended the interview are certainly not unfamiliar with it.

It is a frequent visitor to the interviewer's mouth, but the usual coding is seldom met (at least, I am).

In recent interviews, I have often asked about volatile related issues such as the difference between volatile and sychronized ,volatile usage scenarios ,the principle of volatile implementation , and so on.

Ask these questions in fact, mainly to examine the multi-threaded, lock and other convenient knowledge reserves. Although the use of volatile in our daily coding is not much, but his idea of implementation and some of the concepts behind it is worth learning and thinking.

Example

First, let's look at an example

publicclassextends Thread {        privatestaticbooleanfalse;        publicvoidrun() {        while (!flag) {        }    }    publicstaticvoidmainthrows Exception {        newVolatileExample().start();        Thread.sleep(100);        true;    }}

This piece of code is not long.

    • Declares a Boolean type of static variable flag with an initial value of false;

    • The main function starts a thread volatileexample, which is integrated from the thread class;

    • Remove the volatileexample thread, and of course there is a main thread main;

    • The main thread sleep is 100 milliseconds, and the flag at the rear is true;

So, what do you think of running main?

    • Run through all the code, end?

    • The program has been waiting and won't end?

Let's look at the results of the run

From the results can be found that the main thread after the end of the interface, the left side of the red dot did not disappear, indicating that the program has not ended.

This is because the flag that is read by the volatileexample thread that is started is always false.

Although flag in the main thread has been assigned true, the volatileexample thread ignores it, which is why it involves a problem with visibility.

Visibility of

This assumes that everyone has a certain knowledge of threads and locks.

Sychronized we should have used or learned this is to add an identity to a shared resource in a multithreaded environment, to lock down shared resources, and to prevent multiple threads from entering into inconsistent data operations at the same time.

We usually say that the lock is actually on the surface to achieve a mutually exclusive effect, that is, for the simultaneous existence of thread A and thread B, if this time thread A or lock, then thread B can only be in the next obediently, and so on, this is a mutual exclusion, you do not have me, I did not you!

But the essence of locking is to solve the problem of visibility. First of all, let's not talk about this problem, we first combine the above example to say the problem of visibility. The latter may better understand the nature of locking in conjunction with visibility.

In the Java memory model, it is divided into two blocks of main memory and working memory .

The main memory, mainly the storage of each thread will be used to share variables and so on.

For each thread that has its own storage variable, the working memory is the place. The working memory between the threads is independent of each other and is not visible.

Here, you may already know why the above example program has been running out of state without terminating. Yes, the flag value read by the Volatileexample thread is the value stored in working memory on its own thread, and the flag value in the main thread is updated, but is not visible or perceptible to volatileexample.

So that's when the volatile keyword comes in handy. We add the volatile keyword modifier to the flag variable money. Run the program again

The effect is obvious, and the main thread and volatileexample threads end together.

This is because using the volatile keyword decoration, the variable is forced to read from the main memory and write to the main memory , so that each thread in the operation of the value of this variable is the most fresh data.

At this point, let's review the essence of lock-up just to solve the problem of visibility.

Volatile is forcing all threads to manipulate shared resources from one place, making it possible to read a variable from a copy of each thread to read the variable from the main memory, thereby resolving the visibility issue.

Sychronized also solves the problem of visibility, which does not allow two threads to operate the same shared resource at the same time because it does not guarantee visibility. Therefore, by exclusive mutual exclusion of the way to ensure that they do not have the next execution, so that only one thread at a time to occupy resources, but also indirectly solve the problem of visibility.

Speaking of which, we have to ask another question--atomicity.

Atomic Nature
private int num = 0;num++;

Does the code above match the atomic nature?

Obviously non-conforming, assuming now thread A and thread B two threads,

Thread A reads num=0, prepares to perform num++ operations,

However, before the "+ +" operation has been performed, thread B reads the value of NUM, at this time the value is 0, and then the num++ operation is performed.

Finally, A and b two threads finally get a value of 1,

This is not atomic in nature.

By the following sychronized, the modification is atomic.

sychronized(this) {    num++;}

The reason is still because of the exclusivity of sychronized.

So is volatile guaranteed to be atomic?

The answer is in the negative. The truth is the same as the description without sychronized.

When thread A also finishes executing num++, thread B also accesses the NUM value, gets 0, then executes num++, and eventually two threads get a value of 1.

So what are the usage scenarios for volatile?

Application Scenarios of volatile
    • Volatile is raised when the synchronized performance is low. Now the efficiency of synchronized has been greatly improved, so the significance of volatile existence is small.

    • Today's non-volatile shared variables have the same effect as volatile modified variables when access is not super-frequent.

    • Volatile does not guarantee atomicity, this is not very clear, so it is easy to make mistakes.

    • Volatile can prohibit reordering (sychronized is also possible).

In fact, the related concepts and reordering, happens-before,as-if-serial and so on, confined to space, no longer detailed.

If you feel that reading this article is helpful to you, please click " recommend " button, your " recommendation " will be my biggest writing motivation! If you want to keep an eye on my article, please scan the QR code, follow Jackiezheng's public number, I will push my article to you and share with you the high-quality articles I have read every day.

Concurrency and multithreading-talk about the long-time job interview with less volatile

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.