concept pcall in category java

appears as: pcalls
The Well-Grounded Java Developer

This is an excerpt from Manning's book The Well-Grounded Java Developer.

In fact, there are several different methods that Clojure uses to provide different sorts of concurrency models—futures and pcalls, refs, and agents. Let’s look at each in turn, starting with the simplest.

The next listing sets up a 1-argument function called (wait-with-for). This uses a loop form similar to the one introduced in section 10.3.2. From this, you create a number of 0-argument functions (wait-1), (wait-2), and so on, which you can feed to (pcalls).

Listing 10.9. Parallel calls in Clojure
user=> (defn wait-with-for [limit] (let [counter 1] (loop [ctr counter] (Thread/sleep 500) (println (str "Ctr=" ctr)) (if (< ctr limit) (recur (inc ctr)) ctr)))) #'user/wait-with-for user=> (defn wait-1 [] (wait-with-for 1)) user=> #'user/wait-1 user=> (defn wait-2 [] (wait-with-for 2)) user=> #'user/wait-2 user=> (defn wait-3 [] (wait-with-for 3)) user=> #'user/wait-3 user=> (def wait-seq (pcalls wait-1 wait-2 wait-3)) #'user/wait-seq Ctr=1 Ctr=1 Ctr=1 Ctr=2 Ctr=2 Ctr=3 user=> (first wait-seq) 1 user=> (first (next wait-seq)) 2

With a thread sleep value of only 500 ms, the wait functions complete very quickly. By playing with the timeout (such as by extending it to 10 s), it’s easy to verify that the lazy sequence called wait-seq that is returned by (pcalls) has the described blocking behavior.