This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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