-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
TiMessenger.java
405 lines (350 loc) Β· 12.2 KB
/
TiMessenger.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/**
* Titanium SDK
* Copyright TiDev, Inc. 04/07/2022-Present
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.kroll.common;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
/**
* A messenger interface that maintains a {@link android.os.MessageQueue}, and
* {@link android.os.Looper} but with better primitives for blocking and single
* loop iteration. The TiMessenger also provides information on the main and
* runtime threads and supports posting runnable's on both threads.
*
* TiMessengers have one instance per thread tied by a ThreadLocal. The main
* thread's TiMessenger can be retrieved by calling {@link
* #getMainMessenger()}. The runtime thread's TiMessenger can be retrieved by
* calling {@link #getRuntimeMessenger()}. A TiMessenger can be lazily created/queried for
* the current Thread by calling {@link #getMessenger()}.
*
* To simply send a message, see {@link #sendMessage(Message)} and {@link
* #post(Runnable)}.
*
* In situations where the current thread needs to be blocked while waiting on
* another thread to process a message, see {@link
* #sendBlockingMainMessage(Message, Object)} and {@link
* #sendBlockingRuntimeMessage(Message, Object)}.
*
* To process and dispatch a single message from the message queue, see {@link
* #dispatchMessage()}.
*/
public class TiMessenger implements Handler.Callback
{
private static final String TAG = "TiMessenger";
private static final int MSG_RUN = 3000;
protected static TiMessenger mainMessenger;
protected static ThreadLocal<TiMessenger> threadLocalMessenger = new ThreadLocal<TiMessenger>() {
protected TiMessenger initialValue()
{
if (Looper.myLooper() == null) {
synchronized (threadLocalMessenger)
{
if (Looper.myLooper() == null) {
Looper.prepare();
}
}
}
TiMessenger messenger = new TiMessenger();
long currentThreadId = Thread.currentThread().getId();
if (currentThreadId == Looper.getMainLooper().getThread().getId()) {
mainMessenger = messenger;
}
return messenger;
}
};
protected ArrayBlockingQueue<Message> messageQueue = new ArrayBlockingQueue<>(10);
protected CountDownLatch blockingLatch;
protected AtomicInteger blockingMessageCount = new AtomicInteger(0);
protected Handler.Callback callback;
protected long creationThreadId = -1;
protected Looper looper;
protected Handler handler;
public static final int DEFAULT_TIMEOUT = 50;
public static TiMessenger getMessenger()
{
return threadLocalMessenger.get();
}
/**
* Gets a TiMessenger instance used for sending messages to the main UI thread.
* See {@link #sendBlockingRuntimeMessage(Message, Object)} for more details.
* <p>
* As of Titanium 8.0.0, the JavaScript runtime only supports running on the main thread. This means
* that getMainMessenger() and getRuntimeMessenger() will always return the same TiMessenger instance.
* @return the main UI thread TiMessenger instance.
*/
public static TiMessenger getMainMessenger()
{
return mainMessenger;
}
/**
* Gets a TiMessenger instance used for sending messages to the thread that Titanium's JavaScript
* runtime is running on. See {@link #sendBlockingRuntimeMessage(Message, Object)} for more details.
* <p>
* As of Titanium 8.0.0, the JavaScript runtime only supports running on the main thread. This means
* that getMainMessenger() and getRuntimeMessenger() will always return the same TiMessenger instance.
* @return the KrollRuntime TiMessenger instance.
*/
public static TiMessenger getRuntimeMessenger()
{
return getMainMessenger();
}
public static void postOnMain(Runnable runnable)
{
TiMessenger messenger = getMainMessenger();
if (messenger == null) {
Log.w(TAG, "Unable to post runnable on main thread, main messenger is null");
return;
}
messenger.handler.post(runnable);
}
public static void postOnRuntime(Runnable runnable)
{
postOnMain(runnable);
}
/**
* Sends a message to an {@link java.util.concurrent.ArrayBlockingQueue#ArrayBlockingQueue(int) ArrayBlockingQueue},
* and dispatch messages on the current
* queue while blocking on the passed in AsyncResult. The blocking is done on the Main thread.
* @param message the message to send.
* @return The getResult() value of the AsyncResult put on the message.
*/
public static Object sendBlockingMainMessage(Message message)
{
return threadLocalMessenger.get().sendBlockingMessage(message, getMainMessenger(), null, -1);
}
/**
* Sends a message to an {@link java.util.concurrent.ArrayBlockingQueue#ArrayBlockingQueue(int) ArrayBlockingQueue},
* and dispatch messages on the current
* queue while blocking on the passed in AsyncResult. The blocking is done on the Main thread.
* @param message the message to send.
* @param asyncArg argument to be added to the AsyncResult.
* @return The getResult() value of the AsyncResult put on the message.
*/
public static Object sendBlockingMainMessage(Message message, Object asyncArg)
{
return threadLocalMessenger.get().sendBlockingMessage(message, getMainMessenger(), asyncArg, -1);
}
/**
* Sends a message to an {@link java.util.concurrent.ArrayBlockingQueue#ArrayBlockingQueue(int) ArrayBlockingQueue},
* and dispatch messages on the current
* queue while blocking on the passed in AsyncResult. The blocking is done on the KrollRuntime thread.
* @param message the message to send.
* @return The getResult() value of the AsyncResult put on the message.
*/
public static Object sendBlockingRuntimeMessage(Message message)
{
return sendBlockingMainMessage(message);
}
/**
* Sends a message to an {@link java.util.concurrent.ArrayBlockingQueue#ArrayBlockingQueue(int) ArrayBlockingQueue},
* and dispatch messages on the current
* queue while blocking on the passed in AsyncResult. The blocking is done on the KrollRuntime thread.
* @param message the message to send.
* @param asyncArg the argument to be added to AsyncResult.
* @return The getResult() value of the AsyncResult put on the message.
*/
public static Object sendBlockingRuntimeMessage(Message message, Object asyncArg)
{
return sendBlockingMainMessage(message, asyncArg);
}
/**
* Sends a message to an {@link java.util.concurrent.ArrayBlockingQueue#ArrayBlockingQueue(int) ArrayBlockingQueue},
* and dispatch messages on the current
* queue while blocking on the passed in AsyncResult. The blocking is done on the KrollRuntime thread.
* If maxTimeout > 0, it will throw an error and return when we cannot get the permission from the semaphore within maxTimeout.
* @param message the message to send.
* @param asyncArg the argument to be added to AsyncResult.
* @param maxTimeout the maximum time to wait for a permit from the semaphore, in the unit of milliseconds.
* @return The getResult() value of the AsyncResult put on the message.
*/
public static Object sendBlockingRuntimeMessage(Message message, Object asyncArg, long maxTimeout)
{
return threadLocalMessenger.get().sendBlockingMessage(message, getRuntimeMessenger(), asyncArg, maxTimeout);
}
private TiMessenger()
{
looper = Looper.myLooper();
handler = new Handler(this);
}
/**
* @return the native looper. See {@link android.os.Looper} for more details.
*/
public Looper getLooper()
{
return looper;
}
public Handler getHandler()
{
return handler;
}
/**
* Sends a message to an {@link java.util.concurrent.ArrayBlockingQueue#ArrayBlockingQueue(int) ArrayBlockingQueue}, and dispatch messages on the current
* queue while blocking on the passed in AsyncResult. If maxTimeout > 0 and the cannot get the permission from
* the semaphore within maxTimeout, throw an error and return.
* @param message The message to send.
* @param targetMessenger The TiMessenger to send it to.
* @param asyncArg argument to be added to the AsyncResult put on the message.
* @param maxTimeout the maximum time to wait for a permit from the semaphore.
* @return The getResult() value of the AsyncResult put on the message.
*/
private Object sendBlockingMessage(Message message, TiMessenger targetMessenger, Object asyncArg,
final long maxTimeout)
{
@SuppressWarnings("serial")
AsyncResult wrappedAsyncResult = new AsyncResult(asyncArg) {
@Override
public Object getResult()
{
int timeout = 0;
long elapsedTime = 0;
try {
// TODO: create a multi-semaphore condition
// here so we don't unnecessarily poll
while (!tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
if (messageQueue.size() == 0) {
timeout = 50;
} else {
dispatchPendingMessages();
}
elapsedTime += timeout;
if (maxTimeout > 0 && elapsedTime > maxTimeout) {
setException(new Throwable("getResult() has timed out."));
break;
}
}
} catch (InterruptedException e) {
if (Log.isDebugModeEnabled()) {
Log.e(TAG, "Interrupted waiting for async result", e);
}
dispatchPendingMessages();
}
if (exception != null && Log.isDebugModeEnabled()) {
Log.e(TAG, "Unable to get the result from the blocking message.", exception);
}
return result;
}
@Override
public void setResult(Object result)
{
super.setResult(result);
}
};
blockingMessageCount.incrementAndGet();
message.obj = wrappedAsyncResult;
targetMessenger.sendMessage(message);
Object messageResult = wrappedAsyncResult.getResult();
blockingMessageCount.decrementAndGet();
dispatchPendingMessages();
return messageResult;
}
/**
* Sends this message using one three methods:
* <ul>
* <li>If the current thread is the same thread as the message Handler's
* thread, it is dispatched immediately to the Handler</li>
* <li>If this TiMessenger is currently blocking, it is pushed into the
* internal message queue to be processed by the next call to {@link
* #dispatchMessage()}</li>
* <li>If this TiMessenger is <b>NOT</b> current blocking, it is queued to
* it's Handler normally by using msg.sendToTarget()</li>
* </ul>
*
* @param message The message to send
*/
public void sendMessage(Message message)
{
Handler target = message.getTarget();
long currentThreadId = Thread.currentThread().getId();
long targetThreadId = -1;
if (target != null) {
targetThreadId = target.getLooper().getThread().getId();
}
if (target != null && currentThreadId == targetThreadId) {
target.dispatchMessage(message);
} else {
if (isBlocking()) {
try {
messageQueue.put(message);
} catch (InterruptedException e) {
Log.w(TAG, "Interrupted trying to put new message, sending to handler", e);
message.sendToTarget();
}
} else {
message.sendToTarget();
}
}
}
public void post(Runnable runnable)
{
sendMessage(handler.obtainMessage(MSG_RUN, runnable));
}
public void setCallback(Handler.Callback callback)
{
this.callback = callback;
}
public boolean handleMessage(Message message)
{
if (message.what == MSG_RUN) {
((Runnable) message.obj).run();
return true;
}
if (callback != null) {
return callback.handleMessage(message);
}
return false;
}
public void resetLatch()
{
blockingLatch = new CountDownLatch(1);
}
public boolean isBlocking()
{
return blockingMessageCount.get() > 0;
}
public void dispatchPendingMessages()
{
while (true) {
if (!dispatchMessage()) {
break;
}
}
}
public boolean dispatchMessage()
{
Message message = messageQueue.poll();
if (message == null) {
return false;
}
if (message.getTarget() != null) {
message.getTarget().dispatchMessage(message);
message.recycle();
return true;
}
return false;
}
public boolean dispatchMessage(int timeout, TimeUnit timeUnit)
{
try {
Message message = messageQueue.poll(timeout, timeUnit);
if (message != null) {
Log.d(TAG, "Dispatching message: " + message, Log.DEBUG_MODE);
if (message.getTarget() != null) {
message.getTarget().dispatchMessage(message);
message.recycle();
return true;
}
return false;
}
} catch (InterruptedException e) {
// ignore
}
return false;
}
}