From 218f0385e32499fa4fd1019199a9f4f05be8d80f Mon Sep 17 00:00:00 2001 From: Jose Gomez Date: Sun, 11 Feb 2024 12:34:46 -0600 Subject: [PATCH] fix: ensure we only call clojure.core/realized? on IPending --- src/futurama/core.clj | 26 ++++++++++++++++++++------ src/futurama/protocols.clj | 6 +++++- test/futurama/core_test.clj | 7 ++++--- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/futurama/core.clj b/src/futurama/core.clj index 5234a20..dc0dc37 100644 --- a/src/futurama/core.clj +++ b/src/futurama/core.clj @@ -9,7 +9,7 @@ [futurama.state :as state] [futurama.deferred] [manifold.deferred :as d]) - (:import [clojure.lang Var IDeref IFn] + (:import [clojure.lang Var IDeref IPending IFn] [java.util.concurrent CompletableFuture CompletionException @@ -122,6 +122,10 @@ res-fut#)))) (extend-type Future + proto/AsyncPending + (realized? [fut] + (.isDone ^Future fut)) + proto/AsyncCancellable (cancel [this] (future-cancel this)) @@ -139,7 +143,7 @@ take-cb))] (when-let [cb (commit-handler)] (cond - (realized? fut) + (proto/realized? fut) (let [val (try (.get ^Future fut) (catch Throwable e @@ -167,12 +171,18 @@ impl/Channel (close! [fut] - (when-not (realized? fut) + (when-not (proto/realized? fut) (future-cancel ^Future fut))) (closed? [fut] - (realized? ^Future fut))) + (proto/realized? ^Future fut))) (extend-type IDeref + proto/AsyncPending + (realized? [ref] + (if (instance? IPending ref) + (realized? ref) + true)) + impl/ReadPort (take! [ref handler] (let [^IDeref ref ref @@ -184,7 +194,7 @@ take-cb))] (when-let [cb (commit-handler)] (cond - (realized? ref) + (proto/realized? ref) (let [val (try (deref ref) (catch Throwable e @@ -215,9 +225,13 @@ (when (instance? IFn ref) (ref nil))) (closed? [ref] - (realized? ref))) + (proto/realized? ref))) (extend-type CompletableFuture + proto/AsyncPending + (realized? [fut] + (.isDone ^CompletableFuture fut)) + proto/AsyncCancellable (cancel [this] (future-cancel this)) diff --git a/src/futurama/protocols.clj b/src/futurama/protocols.clj index af337ae..569f2ba 100644 --- a/src/futurama/protocols.clj +++ b/src/futurama/protocols.clj @@ -1,5 +1,9 @@ -(ns futurama.protocols) +(ns futurama.protocols + (:refer-clojure :exclude [realized?])) (defprotocol AsyncCancellable (cancel [this]) (cancelled? [this])) + +(defprotocol AsyncPending + (realized? [this])) diff --git a/test/futurama/core_test.clj b/test/futurama/core_test.clj index 04f4ff7..ab976f5 100644 --- a/test/futurama/core_test.clj +++ b/test/futurama/core_test.clj @@ -363,9 +363,10 @@ (>! c {:foo "bar"}) (delay (future - (let [p (promise)] - (deliver p c) - p))))))))))))) + (atom + (let [p (promise)] + (deliver p c) + p)))))))))))))) (testing "nested non-blocking take - !