It is critical to ensure that threads are started correctly. Thread startup can be misleading because sometimes the code appears to be performing the function correctly, when in fact it may be executing in the wrong thread. It is critical to ensure that threads are started correctly.
The Thread.start()
method starts executing a thread's run()
method in that thread. It is a mistake to directly invoke the run()
method on a Thread
object. When invoked directly, the statements in the run()
method execute in the current thread instead of the newly created thread. Furthermore, if the Thread
object is not constructed from a Runnable
object but rather by instantiating a subclass of Thread
that does not override the run()
method, a call to the subclass's run()
method invokes Thread.run()
which performs a no-opoperation.
Noncompliant Code Example
This noncompliant code example explicitly invokes run()
in the context of the current thread.
Code Block | ||
---|---|---|
| ||
final class Foo implements Runnable {
public void run() {
// ...
}
public static void main(String[] args) {
Foo f = new foo();
new Thread(f).run();
}
}
|
...
This compliant solution correctly uses the start()
method to start a new thread which then executes the run()
method.
Code Block | ||
---|---|---|
| ||
final class Foo implements Runnable {
public void run() {
// ...
}
public static void main(String[] args) {
Foo f = new foo();
new Thread(f).start();
}
}
|
...
EX1: The run()
method may be invoked when unit testing its functionality. Note that a class cannot be tested for multithreaded use by invoking run()
directly.
EX2: When using a Thread
object that implements Runnable
, and you wish requiring to execute the object's run()
method in the current thread, first cast the object should be cast to a Runnable
and then invoke before invoking run()
.
Code Block | ||
---|---|---|
| ||
Thread tthread = new Thread(new Runnable() { public void run() { // ... } }); t// Invoking thread.run(); is bad; the // bad, user prob meant tprogrammer probably meant thread.start() ((Runnable) t).run(); // OK (Admissible) Warning: This does not start a new thread |
Casting a thread to a Runnable
before calling run()
serves to document the intention of explicitly calling Thread.run()
. Adding a disclaimer alongside the invocation is highly recommended.
Risk Assessment
Failing to activate start threads correctly can cause unexpected behavior.
...