reshefm
reshefm

Reputation: 6167

Clojure idiomatic for synching between threads

The scenario I try to resolve is a s follows, I have a testing program that makes a web to a web endpoint on a system.

This test program has a jetty web server running on which it expects a callback from the external system that completes a successful test cycle. In case that the callback is not received during an specific time range (timeout), the test fails.

To achieve this, I want the test runner to wait on an "event" that the jetty handler will set upon callback.

I thought about using java's CyclicBarrier but I wonder if there is an idiomatic way in clojure to solve this.

Thanks

Upvotes: 5

Views: 115

Answers (2)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

In straight Clojure, using an agent that tracks outstanding callbacks would make sense, though in practice I would recommend using Aleph, which is a library for asynchronous web programming that makes even driven handlers rather easy. It produces ring handlers, which sounds like it would fit nicely with your existing code.

Upvotes: 3

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

You can use promise you asked about recently :) Something like this:

(def completion (promise))

; In test runner.
; Wait 5 seconds then fail.
(let [result (deref completion 5000 :fail)]
   (if (= result :success) 
     (println "Great!") 
     (println "Failed :(")))

; In jetty on callback
(deliver completion :success)

Upvotes: 6

Related Questions