Mercurial > lasercutter
view src/clojure/contrib/singleton.clj @ 10:ef7dbbd6452c
added clojure source goodness
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 21 Aug 2010 06:25:44 -0400 |
parents | |
children |
line wrap: on
line source
1 ;;; singleton.clj: singleton functions3 ;; by Stuart Sierra, http://stuartsierra.com/4 ;; April 14, 20096 ;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use7 ;; and distribution terms for this software are covered by the Eclipse8 ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)9 ;; which can be found in the file epl-v10.html at the root of this10 ;; distribution. By using this software in any fashion, you are11 ;; agreeing to be bound by the terms of this license. You must not12 ;; remove this notice, or any other, from this software.15 ;; Change Log:16 ;;17 ;; April 14, 2009: added per-thread-singleton, renamed singleton to18 ;; global-singleton19 ;;20 ;; April 9, 2009: initial version23 (ns24 ^{:author "Stuart Sierra",25 :doc "Singleton functions"}26 clojure.contrib.singleton)28 (defn global-singleton29 "Returns a global singleton function. f is a function of no30 arguments that creates and returns some object. The singleton31 function will call f just once, the first time it is needed, and32 cache the value for all subsequent calls.34 Warning: global singletons are often unsafe in multi-threaded code.35 Consider per-thread-singleton instead."36 [f]37 (let [instance (atom nil)38 make-instance (fn [_] (f))]39 (fn [] (or @instance (swap! instance make-instance)))))41 (defn per-thread-singleton42 "Returns a per-thread singleton function. f is a function of no43 arguments that creates and returns some object. The singleton44 function will call f only once for each thread, and cache its value45 for subsequent calls from the same thread. This allows you to46 safely and lazily initialize shared objects on a per-thread basis.48 Warning: due to a bug in JDK 5, it may not be safe to use a49 per-thread-singleton in the initialization function for another50 per-thread-singleton. See51 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230"52 [f]53 (let [thread-local (proxy [ThreadLocal] [] (initialValue [] (f)))]54 (fn [] (.get thread-local))))