40 lines
1.6 KiB
Plaintext
40 lines
1.6 KiB
Plaintext
With Java 21 the `java.lang.Thread` API was updated with the methods `.ofVirtual` and `.ofPlatform` which return two different implementations
|
|
of the new `Thread.Builder` interface, which can be used to instantiate virtual or platform threads with a builder pattern.
|
|
|
|
|
|
== Why is this an issue?
|
|
|
|
While this can be useful, whenever we want to instantiate and start an unnamed virtual thread, there is a more convenient static method to do so: `Thread.startVirtualThread(Runnable task)`
|
|
|
|
This rule raises an issue every time the form `Thread.ofVirtual().start(task);` is found.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
Thread virtualThread = Thread.ofVirtual().start(task); // Noncompliant `Thread.startVirtualThread` should be used instead
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
Thread virtualThread = Thread.startVirtualThread(task); // Compliant
|
|
Thread unstartedVirtualThread = Thread.ofVirtual().unstarted(task); // Compliant, the thread is unstarted
|
|
Thread namedVirtualThread = Thread.ofVirtual().name("MyThread").start(); // Compliant, the builder pattern is being used to set the name
|
|
Thread platformThread = Thread.ofPlatform().start(task); // Compliant, there is no `Thread.startPlatformThread` method
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* Java Documentation - https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Thread.Builder.html[Thread.Builder]
|
|
|
|
* Java Documentation - https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Thread.html#startVirtualThread(java.lang.Runnable)[Thread.startVirtualThread]
|