gpt4 book ai didi

multithreading - 在 Actor 内部调用 Thread.sleep

转载 作者:行者123 更新时间:2023-12-05 00:27:51 25 4
gpt4 key购买 nike

我有一个函数重试,它基本上看起来像这样(简化):

object SomeObject {
def retry[T](n: Int)(fn: => T): Option[T] = {
val res = try {
Some(fn)
} catch {
case _: Exception => None
}

res match {
case Some(x) => Some(x)
case None =>
if (n > 1)
//make it sleep for a little while
retry(n - 1)(fn)
else None
}
}
}

我需要在尝试之间稍作停顿。有人告诉我,在 actor 内部调用 Thread.sleep(123) 是 Not Acceptable :
class MyActor extends Actor {
//......
def someFunc = {
Thread.sleep(456) // it's not acceptable in an actor, there is another way to do it
}

}

显然,我不知道客户是否会在 Actor 中使用 SomeObject.retry:
class MyActor extends Actor {
//......
def someFunc = {
SomeObject.retry(5)(someRequestToServer) // ops, SomeObject.retry uses Thread.sleep!
}

}

所以,如果我只是添加:
res match {
case Some(x) => Some(x)
case None =>
if (n > 1)
//make it sleep for a little while
Thread.sleep(123) // ops, what if it's being called inside an actor by a client?!
retry(n - 1)(fn)
else None
}
}

这不会是明智的,不是吗?如果没有,我该怎么办?

最佳答案

是的,调用Thread.sleep这是一个坏主意,因为在 Actor 系统中,线程通常是 Actor 之间共享的有限资源。您不希望一个 Actor 调用 sleep 并从其他 Actor 中占用一个线程。

你应该做的是使用 Scheduler (见 docs )让你的 Actor 在 future 的某个时间向自己发送一条消息以重试。为此,您必须将重试代码移出 SomeObject。并进入Actor

class MyActor extends Actor {

import context.system.dispatcher

def receive = {
case DoIt(retries) if retries > 0 =>
SomeObject.attempt(someRequestToServer) match {
case Some(x) => ...
case None =>
context.system.scheduler.scheduleOnce(5.seconds, self, DoIt(retries - 1))
}
}

}

那么如果你使用 SomeObject.try Actor 系统之外
def attempt(retries: Int) = {
SomeObject.attempt(someRequestToServer) match {
case Some(x) => ...
case None if retries > 0 => {
Thread.sleep(123)
attempt(retries - 1)
}
}
}

在哪里 SomeObject.attempt是:
object SomeObject {
def attempt[T](fn: => T): Option[T] =
try {
Some(fn)
} catch {
case _: Exception => None
}
}

关于multithreading - 在 Actor 内部调用 Thread.sleep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19876987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com