Skip to content

Commit ebb4d96

Browse files
committed
avoid deprecated Thread.getId
1 parent bed340a commit ebb4d96

File tree

1 file changed

+32
-1
lines changed
  • src/library/src/main/java/com/github/sbt/junit/jupiter/internal/listeners

1 file changed

+32
-1
lines changed

src/library/src/main/java/com/github/sbt/junit/jupiter/internal/listeners/OutputCapture.java

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@
2525
import java.io.IOException;
2626
import java.io.OutputStream;
2727
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;
2832
import java.util.Objects;
2933
import java.util.Optional;
3034

@@ -139,9 +143,36 @@ private static class SharedProperty {
139143

140144
private static final String NAME = SharedProperty.class.getName();
141145

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+
142168
/** @return A unique identifier for the current thread. */
143169
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+
}
145176
}
146177

147178
/** @return {@code True}, if output capture should be installed. */

0 commit comments

Comments
 (0)