Java Concurrency (i)-Understanding thread safety

Source: Internet
Author: User

Thread not secure

First of all, for example, the thread is unsafe under what circumstances occur: For example, a variable can be accessed by multiple threads, and in the case of a large number of threads concurrently accessing this variable, the order of the threads execution will bring an unpredictable error to the final result.
First define a singleton class Simpleworkinghardsingleton:

public class SimpleWorkingHardSingleton {    private static SimpleWorkingHardSingleton simpleSingleton = new SimpleWorkingHardSingleton();        // 数量    private int count;        private SimpleWorkingHardSingleton() {        count = 0;    }        public static SimpleWorkingHardSingleton getInstance() {        return simpleSingleton;    }    public int getCount() {        return count;    }        public void addCount(int increment) {        this.count += increment;        System.out.println(this.count);    }}

As you can see in this case, if you are running in a multithreaded environment, count is a variable that is manipulated by multiple threads at the same time, example:

for (int i = 0; i < 5; i++) {    new Thread(new Runnable() {        @Override        public void run() {            SimpleWorkingHardSingleton simpleSingleton = SimpleWorkingHardSingleton.getInstance();            simpleSingleton.addCount(1);        }    }).start();}

Look at the output (your results may differ from mine):

32245

The unthinkable result, do not understand why there will be two 2 appear, 1 Where to go, why the output is not 1 2 3 4 5, the following to explain

    1. Why not 1?
      It is possible that a thread calculates the count=1 and then outputs count, at which point a thread hangs, B threads Execute, b threads are self-increment to count, and when a thread is re-output, count has changed, which results in 1 not being output
    2. Why two 2?
      It is possible that a, B, two threads have completed count calculation, then a thread output, the output is suspended immediately after, and then immediately after the B thread output, then the "a" thread must be output the same count, resulting in the occurrence of the same value.
    3. By increasing the number of loops to 100 or 200, you will find that the last output count does not go to 100 or 200
      This is because count++ this operation is not atomic, that is to say, count++ is not a one-time completion, but divided into 3 steps. The first step is to get count; the second step is to add 1 to the value that count points to, and the third step is to write the calculation result back to count. Therefore, if the three steps are mixed with the chaotic factor of the multi-threaded execution sequence, it will lead to unpredictable problems. For example a thread get count is 1, at this time a line Cheng Lima is suspended, b thread gets count also is 1, then a A, a, a, the thread each goes to execute, the last write back Count is 2, which causes count to be less added once.
Thread Safety

In fact, we see the definition of thread security is the key point is correctness, that is, in the multi-threaded environment, regardless of the runtime environment using how to dispatch, the system or class or method can always show the expected consistent behavior, it is thread-safe.

Summarize
    1. In a multithreaded environment, the reason for concurrent thread security is that multiple threads manipulate a shared variable or a set of variables, and the operation of the variables is not atomic, so the order of execution of the threads interferes with the variable.
    2. To ensure thread safety, the workaround:
      • Multiple threads accessing an immutable variable
      • Variables can not be shared by multithreading
      • Synchronous processing of threads (atomic processing)
Reference content
    1. Book "Java Concurrent programming Combat"

Java Concurrency (i)-Understanding thread safety

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.