|
25 | 25 | import java.io.IOException; |
26 | 26 | import java.io.OutputStream; |
27 | 27 | import java.io.PrintStream; |
| 28 | +import java.lang.invoke.MethodHandle; |
| 29 | +import java.lang.invoke.MethodHandles; |
| 30 | +import java.lang.invoke.MethodType; |
| 31 | +import java.util.Arrays; |
28 | 32 | import java.util.Objects; |
29 | 33 | import java.util.Optional; |
30 | 34 |
|
@@ -139,9 +143,36 @@ private static class SharedProperty { |
139 | 143 |
|
140 | 144 | private static final String NAME = SharedProperty.class.getName(); |
141 | 145 |
|
| 146 | + private static final MethodHandle threadIdMethodHandle; |
| 147 | + |
| 148 | + static { |
| 149 | + final String methodName; |
| 150 | + if (Arrays.stream(Thread.class.getMethods()) |
| 151 | + .filter(x -> x.getName() == "threadId") |
| 152 | + .findFirst() |
| 153 | + .isPresent()) { |
| 154 | + methodName = "threadId"; |
| 155 | + } else { |
| 156 | + methodName = "getId"; |
| 157 | + } |
| 158 | + |
| 159 | + try { |
| 160 | + threadIdMethodHandle = |
| 161 | + MethodHandles.lookup() |
| 162 | + .findVirtual(Thread.class, methodName, MethodType.methodType(Long.TYPE)); |
| 163 | + } catch (NoSuchMethodException | IllegalAccessException e) { |
| 164 | + throw new RuntimeException(e); |
| 165 | + } |
| 166 | + } |
| 167 | + |
142 | 168 | /** @return A unique identifier for the current thread. */ |
143 | 169 | String id() { |
144 | | - return ":" + Thread.currentThread().getId(); |
| 170 | + try { |
| 171 | + long value = (long) threadIdMethodHandle.invoke(Thread.currentThread()); |
| 172 | + return ":" + value; |
| 173 | + } catch (Throwable e) { |
| 174 | + throw new RuntimeException(e); |
| 175 | + } |
145 | 176 | } |
146 | 177 |
|
147 | 178 | /** @return {@code True}, if output capture should be installed. */ |
|
0 commit comments