1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.util.internal;
17
18 import io.netty.util.concurrent.EventExecutor;
19 import io.netty.util.concurrent.FastThreadLocal;
20
21 import java.util.concurrent.Executor;
22 import java.util.concurrent.ThreadFactory;
23
24
25
26
27 public final class ThreadExecutorMap {
28
29 private static final FastThreadLocal<EventExecutor> mappings = new FastThreadLocal<EventExecutor>();
30
31 private ThreadExecutorMap() { }
32
33
34
35
36 public static EventExecutor currentExecutor() {
37 return mappings.get();
38 }
39
40
41
42
43 private static void setCurrentEventExecutor(EventExecutor executor) {
44 mappings.set(executor);
45 }
46
47
48
49
50
51 public static Executor apply(final Executor executor, final EventExecutor eventExecutor) {
52 ObjectUtil.checkNotNull(executor, "executor");
53 ObjectUtil.checkNotNull(eventExecutor, "eventExecutor");
54 return new Executor() {
55 @Override
56 public void execute(final Runnable command) {
57 executor.execute(apply(command, eventExecutor));
58 }
59 };
60 }
61
62
63
64
65
66 public static Runnable apply(final Runnable command, final EventExecutor eventExecutor) {
67 ObjectUtil.checkNotNull(command, "command");
68 ObjectUtil.checkNotNull(eventExecutor, "eventExecutor");
69 return new Runnable() {
70 @Override
71 public void run() {
72 setCurrentEventExecutor(eventExecutor);
73 try {
74 command.run();
75 } finally {
76 setCurrentEventExecutor(null);
77 }
78 }
79 };
80 }
81
82
83
84
85
86 public static ThreadFactory apply(final ThreadFactory threadFactory, final EventExecutor eventExecutor) {
87 ObjectUtil.checkNotNull(threadFactory, "threadFactory");
88 ObjectUtil.checkNotNull(eventExecutor, "eventExecutor");
89 return new ThreadFactory() {
90 @Override
91 public Thread newThread(Runnable r) {
92 return threadFactory.newThread(apply(r, eventExecutor));
93 }
94 };
95 }
96 }