onSpinWait​() method of Thread class - Java 9

前端 未结 4 570
傲寒
傲寒 2021-02-05 01:59

While learning Java 9 features I came across a new method of Thread class, called onSpinWait​. As per javadocs, this method is used for this:

4条回答
  •  我在风中等你
    2021-02-05 02:27

    Pure system hinting!

    Reading this article I quote:

    Goals

    Define an API that would allow Java code to hint to the run-time system that it is in a spin loop. The API will be a pure hint, and will carry no semantic behaviour requirements (for example, a no-op is a valid implementation). Allow the JVM to benefit from spin loop specific behaviours that may be useful on certain hardware platforms. Provide both a no-op implementation and an intrinsic implementation in the JDK, and demonstrate an execution benefit on at least one major hardware platform.

    There are many times a thread must be suspended until something outside its scope changes. A (once) common practice was the wait() notify() pattern where there's one thread waiting for the other thread to wake them up.

    There is a big limitation to this, namely, the other thread must be aware that there might be waiting threads and should notify. If the work of the other thread is outside your control, there's no way to get notified.

    The only way would be a spin-wait. let's say you have a program that checks for new emails and notifies the user:

    while(true) {
        while(!newEmailArrived()) {
        }
        makeNotification();
    }
    

    This piece of code will execute millions of times a seconds; spinning over and over, using precious of electricity and CPU power. A common way of doing this would be to wait a few seconds on each iteration.

    while(true) {
        while(!newEmailArrived()) {
            try {
                Thread.sleep(5000);
            } catch(InterruptedException e) {
            }
        }
        makeNotification();
    }
    

    This does a very good job. But in cases where you have to work instantly a sleep may be out of question.

    Java 9 tries to solve this issue by introducing this new method:

    while(true) {
        while(!newEmailArrived()) {
            Thread.onSpinWait();
        }
        makeNotification();
    }
    

    This will work exactly the same as without the method call, but the system is free to lower the process priority; slowing the cycle or reduce electricity on this loop when its resources are needed for other more important things.

提交回复
热议问题