Java Concurrency understand the concept of race conditions as much as the next Java concurrent threads (VII): Thread Security Policy

A brief

Race condition (Race for condition Condition) : depends on the correctness of the calculation execution timing of a plurality of alternating threads, race condition occurs.

Second, common race conditions analysis

The most common race conditions

1. First detection execution

Execution depends on the detection result and the detection result depends on the timing of the execution of multiple threads, and the next execution timing of the plurality of threads are normally not determined not fixed, resulting in the execution result various problems.

 

For the main thread, if you file a does not exist, create a file a, but after judgment file a does not exist, Task thread creates file a, this time the previous judgment result has failed ( to perform main thread dependent on a wrong judgment result ) At this point a file already exists, but the main thread will continue to create a file, resulting in Task thread creates a file is overwritten, the contents of the file is missing and so on.

Multithreaded environment operations on the same file to be locked.

2. initialization delay (that is, most typically singleton)

public class ObjFactory {
    private Obj instance;
    
    public Obj getInstance(){
        if(instance == null){
            instance = new Obj();
        }
        return instance;
    }
}

 

Thread a thread and b simultaneously execute getInstance (), a thread to see the instance is empty, create a new Obj objects, then thread b also need to determine whether the instance is empty, then the instance is empty depends on unpredictable timing: to create a thread, including how long the object Obj and thread scheduling, and if b is detected, instance is empty, then b will also create an instance objects

Like most concurrency errors, race conditions do not always cause problems, but also improper execution timing
Third, solutions

Java Concurrency (VII): Thread Security Policy

Guess you like

Origin www.cnblogs.com/shamo89/p/10314325.html