简体   繁体   English

Java 多线程切换上下文vs提交新任务及监控队列的解决方案

[英]Java multi-thread switching context vs submit new task and solution for monitoring a queue

  • About switching context (synchronizing with wait/notify) between threads and re-submit a task (Callable/Runnable) to Executor service which is better for performance?关于在线程之间切换上下文(与等待/通知同步)并将任务(可调用/可运行)重新提交给对性能更好的执行器服务? as I know switching context need to save/reload thread data but if I re-submit a task to an Executor service, JVM need to re-allocate stack for the submitted task so I think it has same cost with switching context?我知道切换上下文需要保存/重新加载线程数据,但是如果我将任务重新提交给 Executor 服务,JVM 需要为提交的任务重新分配堆栈,所以我认为切换上下文的成本相同?

  • I design a task queue for worker threads put tasks to that and a monitor thread to take the tasks in the queue, submit the tasks to a thread pool (executor service).我为工作线程设计了一个任务队列,将任务放入其中,并设计了一个监控线程来获取队列中的任务,将任务提交到线程池(执行器服务)。 But I considering about when does the monitor thread work?但是我在考虑监控线程什么时候工作? Option 1: Using thread "wait" for monitor thread and worker thread will notify the monitor thread after they put task to the queue.选项1:使用线程“等待”监控线程和工作线程将任务放入队列后通知监控线程。 Option 2: Using a scheduler executor service for monitor thread to check the queue.选项 2:使用调度程序执行器服务监控线程来检查队列。 -> Which option is better (for speed, performance) and with option 2: how often to check the queue is the best? -> 哪个选项更好(速度、性能)以及选项 2:多久检查一次队列是最好的?

many thanks for your help非常感谢您的帮助

  1. An executor is usually backed by a thread pool.执行程序通常由线程池支持。 So the stacks are already allocated.所以堆栈已经被分配了。 Furthermore, a context switch will only take place if the same CPU core has to execute both threads.此外,只有在同一个CPU 内核必须执行两个线程时才会发生上下文切换。 Modern CPUs have multiple cores, so there would be no context switch involved.现代 CPU 具有多个内核,因此不会涉及上下文切换。

    Having said that, there is surely some overhead in transferring work to another thread.话虽如此,将工作转移到另一个线程肯定会有一些开销。 So tasks should be sufficiently coarse-grained and there should be other work that the main thread can perform in the meantime for the pool to be beneficial.所以任务应该是足够粗粒度的,并且在此期间应该有主线程可以执行的其他工作,以便池是有益的。

  2. There is no need to have a monitor thread if the queue itself is synchronized.如果队列本身是同步的,则不需要监控线程。 Have a look at ArrayBlockingQueue for example;例如,看看ArrayBlockingQueue producers can call the put() method (which blocks when no space in the queue is available), and consumers (threads in the pool) call take() , which blocks when no work is available.生产者可以调用put()方法(当队列中没有可用空间时阻塞),消费者(池中的线程)调用take() ,当没有可用工作时阻塞。 This is how ThreadPoolExecutor is implemented (to be precise, it actually calls offer() , so by default doesn't block on the producer side).这就是ThreadPoolExecutor的实现方式(准确地说,它实际上调用了offer() ,因此默认情况下不会在生产者端阻塞)。

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

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