Skip to content

Instantly share code, notes, and snippets.

@bmabey
Created August 8, 2010 00:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bmabey/513376 to your computer and use it in GitHub Desktop.
(ns lazy-seq-and-futures)
(deftype Foo [])
(defn new-foos
([] (new-foos 10000000))
([x]
(take x (repeatedly #(Foo.)))))
; good version - this realizes the lazy-seq foos and the Foos are not retained in memory
(println "Realizing a lazy-seq with doseq...")
(let [foos (new-foos)]
(doseq [foo foos] foo))
(defn realize-it [coll]
(doseq [foo coll] foo))
; good version - this also works as expected and the entire lazy-seq is not retained
(println "Binding the seq locally and realizing it in another function")
(let [foos (new-foos)]
(realize-it foos))
; good version - this has the same behaviour as above- no Foos are kept in memory
(println "Realizing a lazy-seq in the same future it was created in...")
@(future (let [foos (new-foos)]
(doseq [foo foos] foo)))
; BAD VERSION
; when the lazy-seq is created outside of the future that it is realized in
; the Foos are never released from memory. The entire lazy-seq is held in memory
; resulting in an OutOfMemoryError.
(println "Realizing a lazy-seq in a future after it was created...")
(let [foos (new-foos)]
@(future (doseq [foo foos] foo)))
; BAD VERSION
; also gives a OOM...
(println "Realizing a lazy-seq in a future after it was created...")
@(let [foos (new-foos)]
(future (doseq [foo foos] foo)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment