Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by
(defn get-result-from-first-engine
"Performs search on Powells and Cultura and returns the results
which comes first"
(let [result (promise)]
    (doseq [engine ["powells" "cultura"]]
        (future (if-let [engine-result (search query engine)]
            (deliver result engine-result)
    (println "First result: " (deref result 2000 "timed out"))

(defn -main
    [& args]

    (time (do
        (println (search "clojure" "powells"))
        (println (search "clojure" "cultura"))

    (time (get-result-from-first-engine "clojure"))

This code is part of my solution to the first exercise from chapter 9 of "Clojure for the Brave and True". I want to perform the two requests in parallel and get the response of the one who process first.

Two weird things are happening:

  • The time from the parallel is WAY lower than the sequential one, written in main. Result example below. The time difference is so discrepant, that i guess if clojure caches it someway. I didn't use memoize or anything like that.
  • The main doesn't stop running. It holds like if it was waiting for an input or processing something. My theory is that the future doesn't stop running, but i don't know why

Time difference between parallel and sequential:

"Elapsed time: 2185.2716 msecs"
First result:  https://www3.livrariacultura.com.br/clojure-94991222/p
"Elapsed time: 63.5558 msecs"

Thanks for the help in advance

1 Answer

0 votes

The results seem very possible if you have one slow and one fast source?

future uses a background thread that is cached for reuse for up to 1 minute and will prevent the JVM from exiting. You can stop that with (shutdown-agents).

Thanks for the answer. The `(shutdown-agents)` worked :).

About the time question, when I ran sequential, getting the time of each request and the parallel. The parallel took a slight longer all of the times, I believe is because of thread creation and management.

Please, correct me if I'm wrong. Nonetheless, thanks so much for your help!!