对于以下代码中用于阻止IO任务的调度策略,我感到不确定。
使用scheduleWithFixedDelayDispatchTask方法,似乎我将一个接一个地创建任务,累积可能无限期阻塞的任务。我不确定该策略的使用是否正确。
使用scheduleOnceDispatchTask方法,仅在当前阻塞任务执行结束后才重新调度下一个调度任务,而不是累加可以无限期阻塞的任务的执行。
import java.util.concurrent.TimeUnit
// "io.monix" %% "monix-execution" % "2.3.3"
import monix.execution.schedulers.SchedulerService
import monix.execution.{Cancelable, Scheduler}
import scala.concurrent.duration._
import com.tibco.tibrv.Tibrv
object Temp extends App {
val dispatchDelay = 1.milli
val dispatcher = Scheduler.fixedPool(name = "fixed-pool", poolSize = 1)
sys.addShutdownHook {
shutdownAndAwaitTermination(dispatcher)
}
//scheduleWithFixedDelayDispatchTask()
scheduleOnceDispatchTask()
def scheduleWithFixedDelayDispatchTask(): Cancelable = {
dispatcher.scheduleWithFixedDelay(dispatchDelay, dispatchDelay) {
dispatch()
}
}
def scheduleOnceDispatchTask(): Cancelable = {
dispatcher.scheduleOnce(dispatchDelay) {
dispatch()
// reschedule the next dispatch task
scheduleOnceDispatchTask()
}
}
def shutdownAndAwaitTermination(s: SchedulerService)(implicit atMost: FiniteDuration = 10.seconds): Unit = {
s.shutdown()
s.awaitTermination(atMost, Scheduler.global)
}
def dispatch(): Unit = {
/*
Purpose: Dispatch an event; if no event is ready, block.
Remarks: If the queue is not empty, then this call dispatches the event at the head of the
queue, and then returns. If the queue is empty, then this call blocks indefinitely
while waiting for the queue to receive an event.
*/
Tibrv.defaultQueue().dispatch()
println("dispatching arrived event")
}
TimeUnit.SECONDS.sleep(30)
}
我倾向于使用scheduleOnceDispatchTask方法,但是我不知道我认为是否正确以及是否存在性能问题,所以我在这里寻求帮助和意见。