在Java中什么是快速,等待通知或忙等待? [英] What is fast, wait notify or busy wait in Java?

查看:279
本文介绍了在Java中什么是快速,等待通知或忙等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用busy-wait不是一个好的编程习惯,最好尽可能使用同步对象(wait-notify)。但是我想知道一个人是否准备好牺牲cpu周期,然后忙着等待更快或等待通知?

I understand that use of busy-wait is not a good programming practice and preferably synchronized object (wait-notify) should be used whenever possible. But I would like to know if one is ready to sacrifice cpu cycles, then will busy wait be faster or wait-notify ?

我假设wait-notify将涉及对同步对象的内部锁定,并且信号可能来自内核以唤醒线程,使得这种方法比忙碌等待,人们可以连续检查状况,直到满意为止。只要满足此条件(例如,布尔值== true),线程就可以从繁忙的等待中退出。根据我的理解,我感到很忙 - 等待应该更快。

I assume that wait-notify will involve an intrinsic lock over synchronized object and also signal might come from kernel to wake-up the thread, making this approach much slower than a busy-wait, where one could just check a condition continuously till it is satisfied. As soon as this condition is satisfied (e.g. boolean value == true), thread could come out of busy wait. As per my understanding, I feel busy-wait should be faster.

如果其他人可以分享他们的想法并在我的论点错误时纠正我,我将不胜感激。

I would appreciate if others can share their thoughts and correct me if my argument is wrong.

推荐答案

实验表明,如果你等待并等待并通知(在我的硬件上,无论如何),你会更快地看到旗帜。 (详情如下。)差异是 非常非常非常小 ,所以这只适用于非常罕见的应用。例如,股票交易应用程序,公司可以获得他们可以获得的任何优势(争取尽可能在交易所附近找到他们的服务器,以便从交易所获得微网改进等)可能会认为差异是值得的。我也可以想象一些科学应用。

Experimentation suggests that you will see the flag sooner if you busy wait than if you wait and notify (on my hardware, anyway). (Details below.) The difference is very very very very very small and so this would only be applicable to very rare apps. Stock trading apps, for instance, where companies are after any advantage they can get (vying to locate their servers as near the exchange as possible to get microsecond improvements in their network feeds from the exchange and such) might consider the difference worth it. I can imagine some science applications as well.

在绝大多数应用中,差异实际上没有任何区别。

In the vast majority of apps, the difference will be in effect no difference at all.

但是,当然,CPU会发生什么样的核心硬件:

But what happens to the CPU is, of course, that one of the cores hard-pegs:

在影响盒子上的其他进程和权力方面这是不好的数据中心消费。

That's bad in terms of impacting other processes on the box and in terms of power consumption in the data center.

所以:只有在真正重要的情况下才会极度不情愿地使用。

So: Use with extreme reluctance, only in situations where it really matters.

数据(非常小的样本,但代码如下):

Data (very small sample, but the code follows):


Busy Wait:       10631  12350  15278
Wait and Notify: 87299 120964 107204
Delta:           76668 108614  91926

时间在 纳米 秒。十亿分之一秒。上面的平均增量为92403ns(0.092402667毫秒,0.000092403秒)。

Times are in nanoseconds. Billionths of a second. The average delta above is 92403ns (0.092402667 milliseconds, 0.000092403 seconds).

BusyWait.java

public class BusyWait {

    private static class Shared {
        public long setAt;
        public long seenAt;
        public volatile boolean flag = false;
    }

    public static void main(String[] args) {
        final Shared shared = new Shared();
        Thread notifier = new Thread(new Runnable() {
            public void run() {
                System.out.println("Running");
                try {
                    Thread.sleep(500);
                    System.out.println("Setting flag");
                    shared.setAt = System.nanoTime();
                    shared.flag = true;
                }
                catch (Exception e) {
                }
            }
        });
        notifier.start();
        while (!shared.flag) {
        }
        shared.seenAt = System.nanoTime();
        System.out.println("Delay between set and seen: " + (shared.seenAt - shared.setAt));
    }
}

WaitAndNotify.java

public class WaitAndNotify {

    private static class Shared {
        public long setAt;
        public long seenAt;
        public boolean flag = false;
    }

    public static void main(String[] args) {
        (new WaitAndNotify()).test();
    }
    private void test() {
        final Shared shared = new Shared();
        final WaitAndNotify instance = this;
        Thread notifier = new Thread(new Runnable() {
            public void run() {
                System.out.println("Running");
                try {
                    Thread.sleep(500);
                    System.out.println("Setting flag");
                    shared.setAt = System.nanoTime();
                    shared.flag = true;
                    synchronized (instance) {
                        instance.notify();
                    }
                }
                catch (Exception e) {
                }
            }
        });
        notifier.start();
        while (!shared.flag) {
            try {
                synchronized (this) {
                    wait();
                }
            }
            catch (InterruptedException ie) {
            }
        }
        shared.seenAt = System.nanoTime();
        System.out.println("Delay between set and seen: " + (shared.seenAt - shared.setAt));
    }
}

这篇关于在Java中什么是快速,等待通知或忙等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆