Created
August 17, 2017 01:35
-
-
Save kingpong/96b8f9d126a32ec8873bfa63dfb517e9 to your computer and use it in GitHub Desktop.
How to use Hazelcast fully async ICompletableFuture with manifold/deferred
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns scratch.core | |
(:require [chazel.core :as chazel] | |
[manifold.deferred :as d]) | |
(:gen-class) | |
(:import (com.hazelcast.core IMap ICompletableFuture ExecutionCallback))) | |
;; Hazelcast's ICompletableFuture is a Future<> which means it works | |
;; out of the box with manifold/deferred. Unfortunately, though, since it doesn't | |
;; derive CompletableFuture, manifold must block a thread to know when | |
;; the future has been realized. This protocol extension adapts ICompletableFuture | |
;; to manifold's Deferrable protocol to make the Hazelcast async ops purely | |
;; reactive when used with manifold. | |
;; | |
(extend-protocol d/Deferrable | |
ICompletableFuture | |
(to-deferred [^ICompletableFuture cf] | |
(let [d (d/deferred) | |
cb (reify ExecutionCallback | |
(onResponse [_ val] | |
(d/success! d val)) | |
(onFailure [_ err] | |
(d/error! d err)))] | |
(.andThen cf cb) | |
d))) | |
(defn -main | |
[& args] | |
(chazel/cluster-of 1) | |
(let [^IMap m (chazel/hz-map :mymap)] | |
(-> (.putAsync m :foo :bar) | |
(d/chain (fn [_] (.getAsync m :foo))) | |
(d/chain #(println "Got response:" %1)) | |
deref)) | |
(chazel/shutdown)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment