Created
August 5, 2010 23:54
-
-
Save timcharper/510601 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI: the first test passes, the latter test fails (in Clojure 1.2)