Book Image

Clojure Reactive Programming

Book Image

Clojure Reactive Programming

Overview of this book

Table of Contents (19 chapters)
Clojure Reactive Programming
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Bibliography
Index

Clojure futures


The first step toward fixing this issue—that is, to prevent a potentially long-running task from blocking our application—is to create new threads, which do the work and wait for it to complete. This way, we keep the application's main thread free to serve more clients.

Working directly with threads, however, is tedious and error-prone, so Clojure's core library includes futures, which are extremely simple to use:

(def f (clojure.core/future
         (println "doing some expensive work...")
         (Thread/sleep 5000)
         (println "done")
         10))
(println "You'll see me before the future finishes")
;; doing some expensive work...
;; You'll see me before the future finishes
;; done

In the preceding snippet, we invoke the clojure.core/future macro with a body simulating an expensive computation. In this example, it simply sleeps for 5 seconds before returning the value 10. As the output demonstrates, this does not block the main thread, which is free to serve more...