问题描述
我需要在Clojure程序中实现无限操作.我希望语法对于Java程序员也相当合理:
I need to implement an infinite operation in a Clojure program. I hope the syntax is reasonably clear for Java programmers too:
(defn- my-operation
(future
(while @continue
(do things)
(Thread/sleep polling-time)))
这正是我想要的,它在另一个线程中进行操作,因此它不会阻塞主线程,并且还提供了一种清晰,直接的语法,而无需处理本机Java函数,这迫使我使用点特殊形式.
That gives me exactly what I want, the operation in a different thread so it does not block the main one, and also a pretty clear and straightforward syntax without having to deal with native Java functions which would force me to use the dot special form.
但是Java未来的定义是异步计算结果的表示",在这种情况下,我对结果实际上并没有做任何事情.
But the definition of a Java future is a "representation of the result of an asynchronous computation" and in this case, well, I'm not really doing anything with the result.
- 以这种方式使用它们是否错误?
- 与启动我自己的线程相比,是否有任何技术上的差异令我担心?
- 这在语义上是错误的吗?
推荐答案
这将阻塞Clojure管理的线程池中的线程,并用于此类操作.该线程池的预期用途是用于短期运行的操作,因此有点滥用.另外,future
的目的是一次计算一个值,以便可以多次取消引用,这也很容易被滥用.
This will tie up a thread in the thread pool that Clojure manages, and uses for such things. The intended use of that thread pool is for short running operations, so it's kind-of a misuse. Also, the intention behind a future
is to calculate a value once so it can be dereferenced multiple times, so that's kinds-of a misuse too.
对于长时间运行的任务,还有许多其他选择,包括使用Java的Executor框架,内核异步或启动您自己的线程.
There are lots of other options for long running tasks, including using Java's Executor framework, core-async or starting your own thread.
(defonce background-thread (doto (Thread. (fn []
(while @continue
(do things)
(Thread/sleep polling-time))))
(.setDaemon true)
(.start)))
正如其他人提到的那样,可能值得考虑未处理的异常. Stuart Sierra的博客文章是最好的起点.
As others have mentioned, it might be worth thinking about unhandled exceptions. Stuart Sierra's blog post is a great place to start.
future
的文档字符串表示它返回了可以调用deref
的内容.它是与delay
或atom
相同的引用类型,它具有如何获取值的自身语义,而确实,您可以创建一个Future并使其永久运行(如果您看到一个Future).在某些代码中,这意味着您在乎它所产生的价值.
The docstring for future
says that it returns something you can call deref
on. It is a reference type in the same way that delay
or atom
is, with it's own semantics of how it get's a value and while it's true you could just create a future and let it run forever, if you see a future in some code, it implies that you care about the value it produces.
(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?.
这篇关于将Java Future用于无限操作是否错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!