java multithreading first bullet

java memory model

The computing speed of the computer is too far from the speed of its storage and communication subsystems. A lot of time is spent on disk I/O, network communication, or database access.

The benefits of joining the cache:

As the computing speed of the computer's storage device and the processor has a gap of several orders of magnitude, modern computer systems have to add one or more layers of caches whose read and write speeds are as close as possible to the processor's computing speed as memory. Buffer between the processor and the processor: copy the data needed for the operation to the cache, so that the operation can be carried out quickly, and then synchronize from the cache back to the memory when the operation is over, so that the processor does not need to wait for slow memory reads and writes .

image-20201009155814989

The memory structure of a computer system_weibo-CSDN blog

image-20201009155844642

harm:

It introduces a new problem: Cache Coherence. In a multiprocessor system, each processor has its own cache, and they share the same main memory (Main Memory). This kind of system is called a Shared Memory Multiprocessors System (Shared Memory Multiprocessors System), as shown in Figure 12. -1 shown. When the computing tasks of multiple processors all involve the same main memory area, it may lead to inconsistent cache data

In addition to increasing the cache, in order to make full use of the arithmetic unit inside the processor, the processor may optimize the input code out-of-order execution (Out-Of-Order Execution), and the processor will out-of-order after the calculation The result of execution is reorganized to ensure that the result is consistent with the result of sequential execution, but it does not guarantee that the order of calculation of each statement in the program is consistent with the order in the input code, so if there is a calculation task that depends on another calculation task in the middle As a result, its order cannot be guaranteed by the order of the code. Similar to the processor's out-of-order execution optimization, the Java virtual machine's just-in-time compiler also has instruction reorder optimization.

Safety example

If multiple threads access the same shared data without taking synchronization operations, the results of the operations are inconsistent.

The following code demonstrates that 1000 threads perform an auto-increment operation on cnt at the same time, and its value may be less than 1000 after the operation ends.



public class ThreadUnsafeExample {
    
    

    private int cnt = 0;

    public void add() {
    
    
        cnt++;
    }

    public int get() {
    
    
        return cnt;
    }
}
  


public static void main(String[] args) throws InterruptedException {
    
    
    final int threadSize = 1000;
    ThreadUnsafeExample example = new ThreadUnsafeExample();
    final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < threadSize; i++) {
    
    
        executorService.execute(() -> {
    
    
            example.add();
            countDownLatch.countDown();
        });
    }
    countDownLatch.await();
    executorService.shutdown();
    System.out.println(example.get());
}
  

the reason:

Visibility: caused by CPU cache

Visibility: A thread's modification of a shared variable can be seen immediately by another thread.

//线程1执行的代码
int i = 0;
i = 10;
 
//线程2执行的代码
j = i;

Atomicity: caused by time-sharing multiplexing

Atomicity: That is, one operation or multiple operations are either all executed and the execution process will not be interrupted by any factor, or it will not be executed.

Orderliness: caused by reordering

Orderliness: the order of program execution is executed in the order of code. For a simple example, look at the following code:

int i = 0;              
boolean flag = false;
i = 1;                //语句1  
flag = true;          //语句2

Guess you like

Origin blog.csdn.net/weixin_43843172/article/details/109016728