gpt4 book ai didi

interface - 当可调用是 Clojure 函数时,从 ScheduledFutureTask 获取 nil 而不是返回值

转载 作者:行者123 更新时间:2023-12-04 18:14:13 27 4
gpt4 key购买 nike

我正在尝试使用 Executors.newSingleThreadScheduledExecutor() 来安排 Clojure 函数。令人烦恼的是,在生成的 ScheduledFutureTask 上调用 .get() 返回 nil 而不是函数的结果。

我以希基先生对 future 的实现为模型。

(ns my.ns
(:import (java.util.concurrent Executors ThreadFactory TimeUnit)))


(def ^:private thread-pool-scheduler (atom nil))


(def ^:private thread-pool-counter (agent 0))

(defn- get-and-increment-thread-id []
(-> thread-pool-counter (send inc) deref))

(def ^:private thread-factory
(reify ThreadFactory
(newThread [this f]
(let [thread (Thread. f)]
(.setName thread (format "clojure-scheduled-future-thread-pool-%d"
(get-and-increment-thread-id)))
thread))))

(defn scheduled-future-call [^Callable f ^long delay ^TimeUnit unit]
(.schedule (scheduled-futures-executor) (bound-fn* f) delay unit))

(defn start-scheduled-futures-executor! []
(reset! thread-pool-scheduler
(Executors/newSingleThreadScheduledExecutor thread-factory)))

(defn scheduled-futures-executor []
(or @thread-pool-scheduler
(start-scheduled-futures-executor!)))

一切正常,并在适当的时候触发副作用(例如调度 #(println "ok"))。
但是,调用生成的 ScheduledFutureTask 的 get() 方法总是给我 nil
(例如调度 #(+ 5 5))。

我尝试显式扩展 Callable,尝试省略 bound-fn*,但结果是一样的:
(defprotocol ISchedule
(schedule [this delay time-unit]))

(extend Callable
ISchedule
{:schedule (fn [this delay time-unit]
(.schedule (scheduled-futures-executor) this delay time-unit))})

我的直觉是 ScheduledExecutorService 选择 schedule(Runnable, long, TimeUnit) 而不是 schedule(Callable, long, TimeUnit),但不应该输入提示来解决这个问题吗?

非常非常感谢您的帮助或提示!

最佳答案

My intuition is that the ScheduledExecutorService is choosing schedule(Runnable, long, TimeUnit) over schedule(Callable, long, TimeUnit),



我认为你是对的,只有我具体化了 Callable它工作正常。 (我还在 import 语句的类列表中添加了 Callable)。

编辑:我还删除了对 bound-fn* 的调用

一探究竟:
(defn make-callable [f] (reify Callable (call [this] (f))))

(def cat (make-callable (fn [] (println "meeow") "i am a cat")))

(def who-are-you? (scheduled-future-call cat 2 TimeUnit/SECONDS))

(println "Tell me who you are!\n\t" (.get who-are-you?))

输出:
meeow
Tell me who you are!
i am a cat

关于interface - 当可调用是 Clojure 函数时,从 ScheduledFutureTask 获取 nil 而不是返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038221/

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