Detailed programming -21JVM high-performance memory model

Memory model again:

We start talking about a scenario Code:


// 1、 jre/bin/server  放置hsdis动态链接库
//  测试代码 将运行模式设置为-server, 变成死循环   。 没加默认就是client模式,就是正常(可见性问题)
// 2、 通过设置JVM的参数,打印出jit编译的内容 (这里说的编译非class文件),通过可视化工具jitwatch进行查看
// -server -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -XX:+LogCompilation -XX:LogFile=jit.log
//  关闭jit优化-Djava.compiler=NONE
public class VisibilityDemo {
    // 运行标志
    public boolean flag = true;

    // JIT just in time ( --  --)
    public static void main(String[] args) throws InterruptedException {
        VisibilityDemo demo1 = new VisibilityDemo();
        System.out.println("代码开始了");
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                int i = 0;
//                boolean f = demo1.flag;
//                if(f) {
//                    while(true){
//                        i++;
//                    }
//                }
                while (demo1.flag) {
                    synchronized (this) {
                        i++;
                    }
                }
                System.out.println(i);
            }
        });
        thread1.start();

        TimeUnit.SECONDS.sleep(2);
        // 设置is为false,使上面的线程结束while循环
        demo1.flag = false;
        System.out.println("被置为false了.");
    }
}

复制代码

Problems caused by the 1: Why this code does not stop

  • reason1: Possible reasons caused by CPU cache

Problems caused by the 2: how to make him stop right

  • volatile:. 1 in accordance with a predetermined memory model, maintaining visibility. ACC_VOLATILE access control, can ensure that no cache immediately visible.
  • Start parameters -client -Server major difference is that the optimization jit

Visibility problems

1.CPU other cache, resulting in visibility (short)

2. reordering may cause visibility

3. The three modes of operation: compiled, mixed

  • Compiler: bytecode compilation --- --- jit compiler
  • Explanation: some bytecode compiler segments --- --- Assembler
  • Mixed: the process of running, JIT compiler to take effect, the code is optimized for hot spots
while(demo1.flag){
    i++;
}
//优化后的伪代码 --1旁敲侧击。2查看优化后的汇编代码jitwatch
boolean f = demo1.flag
if(f){
    while(true){
        i++;
    }
}
复制代码

Multithreading in question:

  • The resulting non-see
  • The naked eye can not go to the accuracy of the inspection program
  • Different operating platforms have different expressive
  • It is difficult to reproduce the error

From memory to memory model structure

Instruction reordering

The semantics of the Java programming language compiler and allows the processor to perform optimizations that can interact with incorrect synchronization code, resulting in seemingly contradictory behavior.

Meaning memory model

Memory model could describe the behavior of the program

Java programming language memory model by examining the execution trace of each read operation, and check whether the operation was observed to write effective to work according to certain rules.

All results generated by the implementation of the program as long as the memory can be predicted by the model, to achieve any specific implementer, including re-sorting operations and deleting unnecessary synchronization.

Memory model determines what value can be read at each point in the program

The origin of memory model

JVM runtime data area design, multiple memory sections interact bound to be a problem, Java language specification introduced the related memory model.

shared variables shared variables described

It can be shared between threads memory heap or shared memory called all instance fields, static fields and array elements are stored in the heap memory. If at least one write access, then access to the same variable twice the conflict.

The definition of thread operations

操作定义:
write 要写的变量以及要写的值。
read 要读的变量以及可见写入值(由此,我们可以确定可见的值)
lock要锁定的管程(监视器monitor)
unlock 要解锁的管程
外部操作(socket等等)
启动和终止
复制代码

Program sequence: If a program has no data competition, the implementation of the program all look the same order in this specification covers only operating between threads.

For synchronization requirements

  • For unlocking the monitor m and all subsequent operations for locking synchronization m
  • Write volatile variable v, synchronized with all other threads in the subsequent reading of the v
  • Operating with the thread of thread starts in the first synchronous operation
  • Writing a default value for each attribute (0, false, null) synchronized with the operation of each of its thread
  • Thread T1 is the final operation with the thread T2 T1 has been found that the thread end synchronization (isAlive, join can be determined whether the end of the thread)
  • If the interrupted thread T1 T2, T1 interrupt operation of the thread with all other threads found that T2 is interrupted synchronization by throwing interruptException exception, or call Thread.interrupt or Thread.isInterrupt

happens-before occurrence of first principles

happens-before relationship is mainly used for timing sequence occurs between two conflicting emphasis on action, as well as the definition of a Data Race

Specific virtual machine implementation, it is necessary to ensure that the principles established

  • A thread in the thread of each action in the action behind the action happens-before.
  • unlock action happens-before the tube on a subsequent operation with a lock on the tube.
  • Write to a volatile field Read operation happens-before every subsequent to the volatile field
  • Call to start a thread on the subject () method any action happens-before the start of the thread.
  • All the action happens-before any of the other threads of a thread of success () returned from the join on this thread object.
  • If an operation of a happens-before operation to b, and b happens-before operation c, there is a happens-before c

volatile keyword

Visibility issues: the changes to a thread of shared variables, other threads can be seen in a timely manner

根据JMM中规定的happen before和同步原则
对某个volatile字段的写操作happens-before每个后续对该volatile字段的读操作
对volatile变量v的写入,与所有其他线程后续对v的读同步
复制代码
  • To meet these conditions, the volatile keyword have these features:
  • 1, prohibits caching: (volatile variable access control characters will add ACC_VOLATILE
  • 2, instruction volatile variable is not related to reorder.

In the process of final jmm

final在该对象的构造函数中设置对象的字段,当线程看到该对象,将始终看到该对象的final字段的正确构造版本。
伪代码示例:f=new finalDemo(); 读取到f.x一定最新,x为final字段
复制代码
如果在构造函数中设置字段后发生读取,则会看到该final字段分配的值,否则他将看到默认值,
伪代码示例:public finalDemo(){x=1;y=x;} y会等于1
复制代码
读取该工序对象的final成员变量之前,先要读取共享对象
伪代码示例:r = new ReferenceObj();k = r.f; 这两个操作不能重排序。
复制代码
通常static final是不可以修改的字段,然而System.in,System.out和System.err是static final字段,遗留原因,必须允许通过set方法改变,我们将这些字段称为写保护,以区别于普通final字段。
复制代码

Word Tearing byte processing

Update a field or element can not read or update interact with any other field or element. In particular, the update are two threads adjacent elements of the byte array must not interfere or interact with, you do not need to be synchronized to ensure sequential consistency.

Some processors (especially early alphas processor) does not provide the functionality of a single field.

Update byte array in such a processor, if simply read the contents, update the corresponding byte, then write back to memory the entire contents would be illegal.

This problem is sometimes referred to as: "the word split (word tearing)" on a separate update a single byte difficult processor, we need to demand the other way.

Special treatment of double and long

Guess you like

Origin juejin.im/post/5e15e5f4f265da5d1a447568