Learning article: About synchronization in Java

Source: Internet
Author: User
Tags volatile
In our normal development work, more or less can be exposed to multi-threaded programming or some concurrency problems, with the operating system and system hardware upgrades, concurrent programming is more and more used in our development, we use multi-threading the original idea is to be able to make greater use of system resources, However, when we use multithreading, there will be some problems, we first look at a piece of code.

    private static int i = 0;    private static void Increse () {        i++;    }    public static void Main (string[] args) {    thread[] threads = new THREAD[20];        for (int i = 0; i < Threads.length, i++) {            threads[i] = new Thread (new Runnable () {                @Override public                void RU N () {for                    (int j = 0; J < 10000; J + +) {                        Increse ();                    }}            );            Threads[i].start ();        }                while (Thread.activecount () > 1) {            Thread.yield ();        }                System.out.println (i);    }

First look at this code is not a problem, but if in a multi-threaded environment, the result of this code is basically different, this is to open 20 threads, and then each thread call Increse () method pair variable i For an assignment, the expected output should be 200000 , but why is the output different every time? The reason for this is that this place is i++ , which is the root cause of the concurrency problem, and that seems to be a very simple i++ Why is this problem? Here's a simple look at the Java memory model (JMM), first of all, JMM stipulates that each thread runs with a working memory, and then the variable i is stored in the main memory, Each time the thread calculates the data, it goes to the main memory to get the value of the current variable, so simply, after a thread evaluates the variable i , it does not flush the data to the main memory, at which point the other threads have acquired the original value, in other words, Whether the data obtained in this thread is up-to-date is not known. But this is simply from the JMM point of view, i++ This seemingly simple operation actually contains three operations, get the I value, the i self-increment, and then the I to assign the value. It is in these operations, other threads will have a lot of time to do a lot of things, then someone will ask, is it possible to synchronize this i++ operation? Yes, how do you synchronize it?

Some people say volatile i It's okay to use it to modify the variables? Yes, java volatile this keyword does provide a synchronous function, but why is there a change here or no effect? The reason is that if a variable is modified with volatile, it will just let other threads immediately know what the value of the current variable is, here is called 可见性 , but still can not solve the i++ problem of these operations, how to deal with it, and someone proposed to use synchronized this keyword, Have to admit that this keyword is really strong, is able to solve the problem, then we have not considered why this can solve this problem, how to solve, it is still simple to say, first of all synchronized belong to the JVM level, there is this keyword method or code block, and finally will be interpreted as monitorenterand monitorexit instructions, these two bytecode explicitly require a reference type parameter to indicate the object to lock or unlock, like this:

Public synchronized String F () {    //code}synchronized (object) {    //code}

See here, we should be able to understand synchronized why we can solve the problem of the above procedures, but we should also be clear that the concept is 原子性 that, in other words, we are dealing with a number of multithreading problems, we should ensure that some of the data sharing operations are atomic, so as to ensure correctness, See here, I believe you also have a general understanding, then we summarize, in dealing with multi-threaded problems, which points are noteworthy,,, 可见性 原子性 有序性 These points is to ensure that multithreading can be the correct precondition, as to what is ordered, This involves reordering of memory instructions, not within the scope of the discussion, and then later in the discussion.

Here also to point out a problem, is whether we deal with multi-threaded issues, we must synchronize, or must be locked, this is not certain, before the online has a way of joking, is that we deal with multi-threaded problems, sometimes will find that the code is written in a single thread, Of course this is just a joke, but here we can see, is not a single-threaded program will not have these problems? The answer is yes, because the single thread does not have the problem of resource competition, and there is no need to discuss it again.

So when do we need to use synchronization and when do we not need it? Let's take a look at the code

    public string f (string s1, String s2, string s3) {        return s1 + s2 +s3;    }

This is a string concatenation of a method, we have to decompile to see what the JVM is doing here?

Related Article

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.