1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package com.allanbank.mongodb.client.callback;
22
23 import java.util.concurrent.Executor;
24 import java.util.concurrent.RejectedExecutionException;
25
26 import com.allanbank.mongodb.client.message.Reply;
27
28
29
30
31
32
33
34 public class ReplyHandler implements Runnable {
35
36
37 private static final ThreadLocal<Receiver> ourReceiver = new ThreadLocal<Receiver>();
38
39
40
41
42
43
44
45
46
47
48
49
50 public static void raiseError(final Throwable exception,
51 final ReplyCallback replyCallback, final Executor executor) {
52 if (replyCallback != null) {
53 if (executor != null) {
54 try {
55 executor.execute(new ReplyHandler(replyCallback, exception));
56 }
57 catch (final RejectedExecutionException rej) {
58
59 replyCallback.exception(exception);
60 }
61 }
62 else {
63 replyCallback.exception(exception);
64 }
65 }
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79
80 public static void reply(final Receiver receiver, final Reply reply,
81 final ReplyCallback replyCallback, final Executor executor) {
82 if (replyCallback != null) {
83
84
85 final boolean lightWeight = replyCallback.isLightWeight();
86 if (!lightWeight && (executor != null)) {
87 try {
88 executor.execute(new ReplyHandler(replyCallback, reply));
89 }
90 catch (final RejectedExecutionException rej) {
91
92 run(receiver, reply, replyCallback);
93 }
94 }
95 else {
96 run(receiver, reply, replyCallback);
97 }
98 }
99 }
100
101
102
103
104 public static void tryReceive() {
105 final Receiver receiver = ourReceiver.get();
106
107 if (receiver != null) {
108 receiver.tryReceive();
109 }
110 }
111
112
113
114
115
116
117
118
119
120
121
122 private static void run(final Receiver receiver, final Reply reply,
123 final ReplyCallback replyCallback) {
124 final Receiver before = ourReceiver.get();
125 try {
126 ourReceiver.set(receiver);
127 replyCallback.callback(reply);
128 }
129 finally {
130 ourReceiver.set(before);
131 }
132 }
133
134
135 private final Throwable myError;
136
137
138 private final Reply myReply;
139
140
141 private final ReplyCallback myReplyCallback;
142
143
144
145
146
147
148
149
150
151 public ReplyHandler(final ReplyCallback replyCallback, final Reply reply) {
152 super();
153 myReplyCallback = replyCallback;
154 myReply = reply;
155 myError = null;
156 }
157
158
159
160
161
162
163
164
165
166 public ReplyHandler(final ReplyCallback replyCallback,
167 final Throwable exception) {
168 super();
169 myReplyCallback = replyCallback;
170 myError = exception;
171 myReply = null;
172 }
173
174
175
176
177
178
179
180 @Override
181 public void run() {
182 if (myReply != null) {
183 reply(null, myReply, myReplyCallback, null);
184 }
185 else if (myError != null) {
186 raiseError(myError, myReplyCallback, null);
187 }
188 }
189 }