简体   繁体   English

Java计划执行程序服务功能

[英]Java Scheduled Executor Service Capabilities

I'm designing a server in which I need to be able to schedule thousands of tasks. 我正在设计一个服务器,我需要能够安排数千个任务。 The task gets executed every 5 seconds. 任务每5秒执行一次。 Will the scheduledexecutorservice be able to handle the thousands of tasks with good accuracy? scheduledexecutorservice是否能够以高精度处理数千个任务? I'm trying to do the timing in just one thread. 我试图在一个线程中进行计时。 But the actual tasks will be executed in a thread pool. 但实际任务将在线程池中执行。 Thanks 谢谢

I'm unsure exactly how it works so if anyone could clarify that as well it'd be appreciated! 我不确定它究竟是如何工作的,所以如果有人能澄清它,那也值得赞赏!

ScheduledExecutorService is backed by a thread pool. ScheduledExecutorService由线程池支持。 Roughly speaking you can calculate the number of threads required to run tasks concurrently without delays using the following equation: 粗略地说,您可以使用以下等式计算并发运行任务所需的线程数而没有延迟:

minimal number of threads in the pool is equal to average number of tasks executed per second times average task run time 池中的最小线程数等于平均任务运行时间每秒执行的平均任务数

For example on average you start 2 tasks taking 3 seconds (on average) to finish, you need 6 threads. 例如,平均而言,你需要花费3秒(平均)来完成2个任务,你需要6个线程。 Of course this assumes fairly uniform distribution of tasks over time. 当然,这假设任务随着时间的推移相当均匀。

You can also use Executors.newCachedThreadPool() which can theoretically run infinite number of tasks concurrently. 您还可以使用Executors.newCachedThreadPool() ,它理论上可以同时运行无限数量的任务。 Obviously available memory and number of context switches will greatly reduce this number. 显然,可用内存和上下文切换次数将大大减少这个数量。

If your usage scenario is: run thousands of tasks schedule at exact same point in time every five seconds - neither JVM nor any other platform will handle that. 如果您的使用场景是:运行数千个任务,每五秒钟在相同的时间点安排 - JVM和任何其他平台都不会处理这个问题。 Even if you have thousands of threads , you are limited by the number of CPU cores. 即使您有数千个线程 ,您也受到CPU核心数量的限制。 Accuracy is highly dependent on the nature of your tasks (CPU-intensive? blocking I/O?) 准确性在很大程度上取决于您的任务的性质(CPU密集型?阻塞I / O?)

I would suggest that you read the javadocs of scheduler executor service. 我建议您阅读调度程序执行程序服务的javadoc。 Is there any particular point that makes you doubt it's Industrial strength. 是否有任何特殊的观点让你怀疑它的工业实力。 You should use it and measure your performance to check whether it matches your use case. 您应该使用它并测量您的性能以检查它是否与您的用例相匹配。

Also, unless you have strong reason you should not tinker with the implementation of the library class (segregating scheduling and task execution threads on the client side) 此外,除非你有充分的理由,否则你不应该修改库类的实现(在客户端隔离调度和任务执行线程)

However, you should evaluate using a library like quartz if your scheduling criteria are expected to get complicated - beyond the basic use cases provided by the scheduler executor service. 但是,如果您的调度标准变得复杂,则应使用像quartz这样的库进行评估 - 超出调度程序执行程序服务提供的基本用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM