Thread.sleep()VS Executor.scheduleWithFixedDelay() [英] Thread.sleep() VS Executor.scheduleWithFixedDelay()

查看:125
本文介绍了Thread.sleep()VS Executor.scheduleWithFixedDelay()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:每隔一段时间执行一些代码。

Goal: Execute certain code every once in a while.

问题:就性能而言,是否存在显着差异:

Question: In terms of performance, is there a significant difference between:

while(true) {
    execute();
    Thread.sleep(10 * 1000);
}

executor.scheduleWithFixedDelay(runnableWithoutSleep, 0, 10, TimeUnit.SECONDS);

当然,后者选项更加犹太洁净。然而,我想知道我是否应该开始一项名为花几天时间重构遗留代码以告别Thread.sleep()的冒险。

Of course, the latter option is more kosher. Yet, I would like to know whether I should embark on an adventure called "Spend a few days refactoring legacy code to say goodbye to Thread.sleep()".

更新:
此代码在超级/超级/超高负载环境中运行。

Update: This code runs in super/mega/hyper high-load environment.

推荐答案

你正在处理睡眠问题时间称为几十秒。通过改变你的睡眠选项可能节省的费用可能是纳秒或微秒。

You're dealing with sleep times termed in tens of seconds. The possible savings by changing your sleep option here is likely nanoseconds or microseconds.

我每次都更喜欢后者的风格,但是如果你有前者并且它会去你需要付出很多代价才能改变它,改善性能并不是一个特别好的理由。

I'd prefer the latter style every time, but if you have the former and it's going to cost you a lot to change it, "improving performance" isn't a particularly good justification.

编辑 re:8000线程

EDIT re: 8000 threads

8000个线程非常多;我可能会移动到计划执行程序,以便您可以控制系统上的负载量。关于不同唤醒时间的观点需要注意,尽管我认为更大的风险是线程踩踏,所有线程都在沉睡,然后紧密连续醒来并争夺所有系统资源。

8000 threads is an awful lot; I might move to the scheduled executor just so that you can control the amount of load put on your system. Your point about varying wakeup times is something to be aware of, although I would argue that the bigger risk is a stampede of threads all sleeping and then waking in close succession and competing for all the system resources.

我会花时间把它们全部放在一个固定的线程池预定执行器中。只有最多有限的资源(例如,#cores,或#IO路径)可以同时运行多个,以及一些可以获取任何slop。这将以延迟为代价为您提供良好的吞吐量。

I would spend the time to throw these all in a fixed thread pool scheduled executor. Only have as many running concurrently as you have available of the most limited resource (for example, # cores, or # IO paths) plus a few to pick up any slop. This will give you good throughput at the expense of latency.

使用 Thread.sleep()方法,它将非常难以控制正在发生的事情,你可能会失去吞吐量延迟。

With the Thread.sleep() method it will be very hard to control what is going on, and you will likely lose out on both throughput and latency.

如果你需要更详细的建议,你可能需要更详细地描述你想要做的事情。

If you need more detailed advice, you'll probably have to describe what you're trying to do in more detail.

这篇关于Thread.sleep()VS Executor.scheduleWithFixedDelay()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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