Mercurial > lasercutter
diff 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 diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/clojure/contrib/singleton.clj Sat Aug 21 06:25:44 2010 -0400 1.3 @@ -0,0 +1,54 @@ 1.4 +;;; singleton.clj: singleton functions 1.5 + 1.6 +;; by Stuart Sierra, http://stuartsierra.com/ 1.7 +;; April 14, 2009 1.8 + 1.9 +;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use 1.10 +;; and distribution terms for this software are covered by the Eclipse 1.11 +;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) 1.12 +;; which can be found in the file epl-v10.html at the root of this 1.13 +;; distribution. By using this software in any fashion, you are 1.14 +;; agreeing to be bound by the terms of this license. You must not 1.15 +;; remove this notice, or any other, from this software. 1.16 + 1.17 + 1.18 +;; Change Log: 1.19 +;; 1.20 +;; April 14, 2009: added per-thread-singleton, renamed singleton to 1.21 +;; global-singleton 1.22 +;; 1.23 +;; April 9, 2009: initial version 1.24 + 1.25 + 1.26 +(ns 1.27 + ^{:author "Stuart Sierra", 1.28 + :doc "Singleton functions"} 1.29 + clojure.contrib.singleton) 1.30 + 1.31 +(defn global-singleton 1.32 + "Returns a global singleton function. f is a function of no 1.33 + arguments that creates and returns some object. The singleton 1.34 + function will call f just once, the first time it is needed, and 1.35 + cache the value for all subsequent calls. 1.36 + 1.37 + Warning: global singletons are often unsafe in multi-threaded code. 1.38 + Consider per-thread-singleton instead." 1.39 + [f] 1.40 + (let [instance (atom nil) 1.41 + make-instance (fn [_] (f))] 1.42 + (fn [] (or @instance (swap! instance make-instance))))) 1.43 + 1.44 +(defn per-thread-singleton 1.45 + "Returns a per-thread singleton function. f is a function of no 1.46 + arguments that creates and returns some object. The singleton 1.47 + function will call f only once for each thread, and cache its value 1.48 + for subsequent calls from the same thread. This allows you to 1.49 + safely and lazily initialize shared objects on a per-thread basis. 1.50 + 1.51 + Warning: due to a bug in JDK 5, it may not be safe to use a 1.52 + per-thread-singleton in the initialization function for another 1.53 + per-thread-singleton. See 1.54 + http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230" 1.55 + [f] 1.56 + (let [thread-local (proxy [ThreadLocal] [] (initialValue [] (f)))] 1.57 + (fn [] (.get thread-local))))