view src/clojure/lang/Atom.java @ 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 /**
2 * Copyright (c) Rich Hickey. All rights reserved.
3 * The use and distribution terms for this software are covered by the
4 * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
5 * which can be found in the file epl-v10.html at the root of this distribution.
6 * By using this software in any fashion, you are agreeing to be bound by
7 * the terms of this license.
8 * You must not remove this notice, or any other, from this software.
9 **/
11 /* rich Jan 1, 2009 */
13 package clojure.lang;
15 import java.util.concurrent.atomic.AtomicReference;
17 final public class Atom extends ARef{
18 final AtomicReference state;
20 public Atom(Object state){
21 this.state = new AtomicReference(state);
22 }
24 public Atom(Object state, IPersistentMap meta){
25 super(meta);
26 this.state = new AtomicReference(state);
27 }
29 public Object deref(){
30 return state.get();
31 }
33 public Object swap(IFn f) throws Exception{
34 for(; ;)
35 {
36 Object v = deref();
37 Object newv = f.invoke(v);
38 validate(newv);
39 if(state.compareAndSet(v, newv))
40 {
41 notifyWatches(v, newv);
42 return newv;
43 }
44 }
45 }
47 public Object swap(IFn f, Object arg) throws Exception{
48 for(; ;)
49 {
50 Object v = deref();
51 Object newv = f.invoke(v, arg);
52 validate(newv);
53 if(state.compareAndSet(v, newv))
54 {
55 notifyWatches(v, newv);
56 return newv;
57 }
58 }
59 }
61 public Object swap(IFn f, Object arg1, Object arg2) throws Exception{
62 for(; ;)
63 {
64 Object v = deref();
65 Object newv = f.invoke(v, arg1, arg2);
66 validate(newv);
67 if(state.compareAndSet(v, newv))
68 {
69 notifyWatches(v, newv);
70 return newv;
71 }
72 }
73 }
75 public Object swap(IFn f, Object x, Object y, ISeq args) throws Exception{
76 for(; ;)
77 {
78 Object v = deref();
79 Object newv = f.applyTo(RT.listStar(v, x, y, args));
80 validate(newv);
81 if(state.compareAndSet(v, newv))
82 {
83 notifyWatches(v, newv);
84 return newv;
85 }
86 }
87 }
89 public boolean compareAndSet(Object oldv, Object newv){
90 validate(newv);
91 boolean ret = state.compareAndSet(oldv, newv);
92 if(ret)
93 notifyWatches(oldv, newv);
94 return ret;
95 }
97 public Object reset(Object newval){
98 Object oldval = state.get();
99 validate(newval);
100 state.set(newval);
101 notifyWatches(oldval, newval);
102 return newval;
103 }
104 }