简体   繁体   English

Java ScheduledExecutorService生产者\\消费者

[英]Java ScheduledExecutorService producer\consumer

I have the next project: 我有下一个项目:

Spring(3.2)-based Web application(Tomcat 7), in background I have several tasks. 基于Spring(3.2)的Web应用程序(Tomcat 7),在后台我有几个任务。

I have a queue with some information for processing. 我有一些要处理的信息的队列。 This queue is updating periodically(but just when it empty). 该队列定期更新(但仅在它为空时更新)。

Also I have several threads that enqueue periodically data from this queue and process. 另外,我有几个线程会定期从此队列和进程中排队数据。

For scheduling I wanted to use ScheduledExecutorService. 对于调度,我想使用ScheduledExecutorService。

I have several problems\\questions: 我有几个问题\\问题:

  1. How to keep this queue? 如何保持这个队列? As I think it should be global. 我认为这应该是全球性的。 Should I make it static in some "holder" class? 我应该在某些“ holder”类中使其静态吗? Won't be this a poor desing? 这不是可怜的打算吗?

  2. Where will be the good place for initializing this queue and all the task with ScheduledExecutorService? 使用ScheduledExecutorService初始化此队列和所有任务的好地方在哪里? Is ServletContextLoadingListener a good place for it? ServletContextLoadingListener适合吗? Are there any ways to init this with Spring? 有什么方法可以用Spring初始化它吗?

  3. Should I use several ScheduledExecutorService instances if I need to control the number of consumer threads exactly? 如果需要精确控制使用者线程的数量,是否应该使用几个ScheduledExecutorService实例?

  4. Will ArrayBlockingQueue be good for this case? ArrayBlockingQueue是否适合这种情况?

  1. You can use an ordinary class and let spring manage it with the scope singleton . 您可以使用普通类,并让spring用作用域singleton对其进行管理。
  2. You can configure the bean with an init-method in spring configuration or implement the InitializingBean interface in your class. 您可以在spring配置中使用init-method配置bean,或者在您的类中实现InitializingBean接口。
  3. The thread number for ScheduledExecutorService is configurable via the constructor arguments. ScheduledExecutorService的线程号可通过构造函数参数进行配置。 If you have tasks of several types and want to run them in separate thread pools, you can use multiple ScheduledExecutorService instances. 如果您具有多种类型的任务,并希望在单独的线程池中运行它们,则可以使用多个ScheduledExecutorService实例。 However, if all your task are of the same type, I don't see the need for multiple ScheduledExecutorService instances. 但是,如果您的所有任务都属于同一类型,那么我看不到需要多个ScheduledExecutorService实例。
  4. The ScheduledThreadPoolExecutor provided within JDK has an internal working queue of class java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue.DelayedWorkQueue (and it is not configurable). JDK中提供的ScheduledThreadPoolExecutor具有一个内部工作队列,该类的类为java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue.DelayedWorkQueue (并且它不可配置)。 I am not sure where do you put the ArrayBlockingQueue. 我不确定您将ArrayBlockingQueue放在哪里。

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

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