Skip to content

Instantly share code, notes, and snippets.

@timcharper
Created August 5, 2010 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timcharper/510601 to your computer and use it in GitHub Desktop.
Save timcharper/510601 to your computer and use it in GitHub Desktop.
(ns clojure.lazy-seq-head-retention-test
(:use [clojure.test])
(:import (java.lang.ref WeakReference)
(java.lang Thread)
(java.util Date)))
(def test-sequence-length 500)
(def objects-per-sequence 100)
(defn- get-released-time [weak-reference]
(future
(loop []
(if (.get weak-reference)
(do
(.gc (Runtime/getRuntime))
(Thread/sleep 100)
(recur))
(Date.)))))
(defn- many-objects []
"returns a lazy sequence that contains <test-items> # dates
We can't directly force the garbage collector to run (only signal
it to do so). To overcome this, we further encourage it by
allocating a multitude of objects. This appears to be reliable, but
has not been tested in a wide-array of heterogeneous environments."
(take test-sequence-length (repeatedly (fn []
(Thread/sleep 1)
(doall
(take objects-per-sequence (repeatedly #(Date.))))))))
;; potentially brittle :( I can't think of a better way to test this right now, however.
(deftest lazy-seq-head-retention
(testing "should not retain the head when consuming a lazy sequence with doseq"
(let [objects (many-objects)
head-released-time (get-released-time (WeakReference. (first objects)))
completion-time (do
(doseq [obj objects] nil)
(Date.))]
(is (.before @head-released-time completion-time))))
(testing "should not retain the head when consuming a lazy sequence with doseq inside a future"
(let [objects (many-objects)
head-released-time (get-released-time (WeakReference. (first objects)))
completion-time (do
@(future
(doseq [obj objects] nil))
(Date.))]
(is (.before @head-released-time completion-time)))))
@timcharper
Copy link
Author

FYI: the first test passes, the latter test fails (in Clojure 1.2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment