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 functions
3 ;; by Stuart Sierra, http://stuartsierra.com/
4 ;; April 14, 2009
6 ;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use
7 ;; and distribution terms for this software are covered by the Eclipse
8 ;; 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 this
10 ;; distribution. By using this software in any fashion, you are
11 ;; agreeing to be bound by the terms of this license. You must not
12 ;; remove this notice, or any other, from this software.
15 ;; Change Log:
16 ;;
17 ;; April 14, 2009: added per-thread-singleton, renamed singleton to
18 ;; global-singleton
19 ;;
20 ;; April 9, 2009: initial version
23 (ns
24 ^{:author "Stuart Sierra",
25 :doc "Singleton functions"}
26 clojure.contrib.singleton)
28 (defn global-singleton
29 "Returns a global singleton function. f is a function of no
30 arguments that creates and returns some object. The singleton
31 function will call f just once, the first time it is needed, and
32 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-singleton
42 "Returns a per-thread singleton function. f is a function of no
43 arguments that creates and returns some object. The singleton
44 function will call f only once for each thread, and cache its value
45 for subsequent calls from the same thread. This allows you to
46 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 a
49 per-thread-singleton in the initialization function for another
50 per-thread-singleton. See
51 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))))