-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathEventThread.java
76 lines (64 loc) · 1.92 KB
/
EventThread.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
package io.socket.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread for event loop. All non-background tasks run within this thread.
*/
public class EventThread extends Thread {
private static final Logger logger = Logger.getLogger(EventThread.class.getName());
private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
thread = new EventThread(runnable);
thread.setName("EventThread");
thread.setDaemon(Thread.currentThread().isDaemon());
return thread;
}
};
private static EventThread thread;
private static final ExecutorService service = Executors.newSingleThreadExecutor(THREAD_FACTORY);
private EventThread(Runnable runnable) {
super(runnable);
}
/**
* check if the current thread is EventThread.
*
* @return true if the current thread is EventThread.
*/
public static boolean isCurrent() {
return currentThread() == thread;
}
/**
* Executes a task in EventThread.
*
* @param task
*/
public static void exec(Runnable task) {
if (isCurrent()) {
task.run();
} else {
nextTick(task);
}
}
/**
* Executes a task on the next loop in EventThread.
*
* @param task
*/
public static void nextTick(final Runnable task) {
service.execute(new Runnable() {
@Override
public void run() {
try {
task.run();
} catch (Throwable t) {
logger.log(Level.SEVERE, "Task threw exception", t);
throw t;
}
}
});
}
}