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