/
Agent.java
287 lines (241 loc) · 6.43 KB
/
Agent.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Nov 17, 2007 */
package clojure.lang;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
public class Agent extends ARef {
static class ActionQueue {
public final IPersistentStack q;
public final Throwable error; // non-null indicates fail state
static final ActionQueue EMPTY = new ActionQueue(PersistentQueue.EMPTY, null);
public ActionQueue( IPersistentStack q, Throwable error )
{
this.q = q;
this.error = error;
}
}
static final Keyword CONTINUE = Keyword.intern(null, "continue");
static final Keyword FAIL = Keyword.intern(null, "fail");
volatile Object state;
AtomicReference<ActionQueue> aq = new AtomicReference<ActionQueue>(ActionQueue.EMPTY);
volatile Keyword errorMode = CONTINUE;
volatile IFn errorHandler = null;
final private static AtomicLong sendThreadPoolCounter = new AtomicLong(0);
final private static AtomicLong sendOffThreadPoolCounter = new AtomicLong(0);
volatile public static ExecutorService pooledExecutor =
Executors.newFixedThreadPool(2 + Runtime.getRuntime().availableProcessors(),
createThreadFactory("clojure-agent-send-pool-%d", sendThreadPoolCounter));
volatile public static ExecutorService soloExecutor = Executors.newCachedThreadPool(
createThreadFactory("clojure-agent-send-off-pool-%d", sendOffThreadPoolCounter));
final static ThreadLocal<IPersistentVector> nested = new ThreadLocal<IPersistentVector>();
private static ThreadFactory createThreadFactory(final String format, final AtomicLong threadPoolCounter) {
return new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setName(String.format(format, threadPoolCounter.getAndIncrement()));
return thread;
}
};
}
public static void shutdown(){
soloExecutor.shutdown();
pooledExecutor.shutdown();
}
static class Action implements Runnable{
final Agent agent;
final IFn fn;
final ISeq args;
final Executor exec;
public Action(Agent agent, IFn fn, ISeq args, Executor exec){
this.agent = agent;
this.args = args;
this.fn = fn;
this.exec = exec;
}
void execute(){
try
{
exec.execute(this);
}
catch(Throwable error)
{
if(agent.errorHandler != null)
{
try
{
agent.errorHandler.invoke(agent, error);
}
catch(Throwable e) {} // ignore errorHandler errors
}
}
}
static void doRun(Action action){
try
{
nested.set(PersistentVector.EMPTY);
Throwable error = null;
try
{
Object oldval = action.agent.state;
Object newval = action.fn.applyTo(RT.cons(action.agent.state, action.args));
action.agent.setState(newval);
action.agent.notifyWatches(oldval,newval);
}
catch(Throwable e)
{
error = e;
}
if(error == null)
{
releasePendingSends();
}
else
{
nested.set(null); // allow errorHandler to send
if(action.agent.errorHandler != null)
{
try
{
action.agent.errorHandler.invoke(action.agent, error);
}
catch(Throwable e) {} // ignore errorHandler errors
}
if(action.agent.errorMode == CONTINUE)
{
error = null;
}
}
boolean popped = false;
ActionQueue next = null;
while(!popped)
{
ActionQueue prior = action.agent.aq.get();
next = new ActionQueue(prior.q.pop(), error);
popped = action.agent.aq.compareAndSet(prior, next);
}
if(error == null && next.q.count() > 0)
((Action) next.q.peek()).execute();
}
finally
{
nested.set(null);
}
}
public void run(){
doRun(this);
}
}
public Agent(Object state) {
this(state,null);
}
public Agent(Object state, IPersistentMap meta) {
super(meta);
setState(state);
}
boolean setState(Object newState) {
validate(newState);
boolean ret = state != newState;
state = newState;
return ret;
}
public Object deref() {
return state;
}
public Throwable getError(){
return aq.get().error;
}
public void setErrorMode(Keyword k){
errorMode = k;
}
public Keyword getErrorMode(){
return errorMode;
}
public void setErrorHandler(IFn f){
errorHandler = f;
}
public IFn getErrorHandler(){
return errorHandler;
}
synchronized public Object restart(Object newState, boolean clearActions){
if(getError() == null)
{
throw Util.runtimeException("Agent does not need a restart");
}
validate(newState);
state = newState;
if(clearActions)
aq.set(ActionQueue.EMPTY);
else
{
boolean restarted = false;
ActionQueue prior = null;
while(!restarted)
{
prior = aq.get();
restarted = aq.compareAndSet(prior, new ActionQueue(prior.q, null));
}
if(prior.q.count() > 0)
((Action) prior.q.peek()).execute();
}
return newState;
}
public Object dispatch(IFn fn, ISeq args, Executor exec) {
Throwable error = getError();
if(error != null)
{
throw Util.runtimeException("Agent is failed, needs restart", error);
}
Action action = new Action(this, fn, args, exec);
dispatchAction(action);
return this;
}
static void dispatchAction(Action action){
LockingTransaction trans = LockingTransaction.getRunning();
if(trans != null)
trans.enqueue(action);
else if(nested.get() != null)
{
nested.set(nested.get().cons(action));
}
else
action.agent.enqueue(action);
}
void enqueue(Action action){
boolean queued = false;
ActionQueue prior = null;
while(!queued)
{
prior = aq.get();
queued = aq.compareAndSet(prior, new ActionQueue((IPersistentStack)prior.q.cons(action), prior.error));
}
if(prior.q.count() == 0 && prior.error == null)
action.execute();
}
public int getQueueCount(){
return aq.get().q.count();
}
static public int releasePendingSends(){
IPersistentVector sends = nested.get();
if(sends == null)
return 0;
for(int i=0;i<sends.count();i++)
{
Action a = (Action) sends.valAt(i);
a.agent.enqueue(a);
}
nested.set(PersistentVector.EMPTY);
return sends.count();
}
}