concurrent

Early computer does not include the system, from the beginning to the end only to execute a program, every time the advent of the computer operating system can run multiple applications in different processes, and to separate process allocation of various resources, including memory, file handles, etc., in the process can be coarse-grained communication mechanism between exchange data; However, inter-process communication is expensive, so a lightweight process was born: thread. Most operating systems currently use thread as the basic scheduling unit, and all threads in the same process share the memory address of the process, so a more fine-grained data sharing mechanism is needed to ensure thread safety

Security issues

Thread security is very complex. Without proper synchronization, the order of execution of multiple threads can be unpredictable, which means that the results of your program may exceed your expectations, such as:

public class UnsafeSequence {
    private int value;
    
    /** value increment **/
    public int getNext(a){
        returnvalue++; }}Copy the code

Value++ seems to be an atomic operation, but it is actually divided into three steps:

  • Read the value
  • Add the value 1
  • Assign the result of the calculation to value

Different threads might result in the following sequence of execution

The result is that the same value is returned in different threads, and the final result may be less than 1000. This is a very common and easily overlooked concurrency safety issue calledRace Condition.

Let’s try to fix this method so that it returns the correct result even in a multi-threaded environment

public class UnsafeSequence {
    private int value;
    
    /** value increment **/
    public synchronized int getNext(a){
        returnvalue++; }}Copy the code

The simplest modification is to define the getNext() method as a synchronized method, with the synchronized keyword.

Activity problem

Safety means “nothing bad will ever happen,” while activity means “something right will eventually happen.” For example, unintentionally creating infinite loops, deadlocks, starvation, and live locks are all active problems. How to avoid these problems will be explained later in this article. This article is just a brief introduction to concurrency problems in Java, so that you have a simple idea