使用Java未来进行无限操作是错误的吗?

Jac*_*cob 3 java multithreading future clojure java.util.concurrent

我需要在Clojure程序中实现无限操作.我希望Java程序员的语法也相当清晰:

(defn- my-operation
    (future
        (while @continue
            (do things)
            (Thread/sleep polling-time)))
Run Code Online (Sandbox Code Playgroud)

这给了我我想要的东西,在不同的线程中的操作,因此它不会阻止主要的,并且还有一个非常清晰和直接的语法,而不必处理将迫使我使用点特殊形式的本机Java函数.

但Java未来的定义是"异步计算结果的表示",在这种情况下,我实际上并没有对结果做任何事情.

  • 以这种方式使用它们是错误的吗?
  • 与启动我自己的Thread相比,是否有任何技术差异应该让我担心?
  • 这在语义上是错误的吗?

l0s*_*t3d 5

这将占用Clojure管理的线程池中的一个线程,并用于此类事情.该线程池的预期用途是用于短期运行操作,因此它是一种误用.此外,a背后的意图future是计算一次值,以便可以多次解除引用,这样也是一种误用.

对于长时间运行的任务,还有许多其他选项,包括使用Java的Executor框架,核心异步或启动自己的线程.

(defonce background-thread (doto (Thread. (fn []
                                            (while @continue
                                              (do things)
                                              (Thread/sleep polling-time))))
                             (.setDaemon true)
                             (.start)))
Run Code Online (Sandbox Code Playgroud)

正如其他人所提到的,可能值得考虑未处理的异常.Stuart Sierra的博客文章是一个很好的起点.

文档字符串future表示它返回了您可以调用的deref内容.它是一种引用类型,它delay或者atom是它自己的语义,它是如何得到一个值的,而它是真的,你可以创建一个未来并让它永远运行,如果你看到一些代码中的未来,它暗示你关心它产生的价值.

(clojure.repl/doc future)
-------------------------
clojure.core/future
([& body])
Macro
  Takes a body of expressions and yields a future object that will
  invoke the body in another thread, and will cache the result and
  return it on all subsequent calls to deref/@. If the computation has
  not yet finished, calls to deref/@ will block, unless the variant of
  deref with timeout is used. See also - realized?.
Run Code Online (Sandbox Code Playgroud)