Direct call to a run() methodΒΆ
ID: java/call-to-thread-run
Kind: problem
Severity: recommendation
Precision: high
Tags:
- reliability
- correctness
- concurrency
- external/cwe/cwe-572
Query suites:
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
A direct call of a Thread objectβs run method does not start a separate thread. The method is executed within the current thread. This is an unusual use because Thread.run() is normally intended to be called from within a separate thread.
RecommendationΒΆ
To execute Runnable.run from within a separate thread, do one of the following:
Construct a
Threadobject using theRunnableobject, and callstarton theThreadobject.Define a subclass of a
Threadobject, and override the definition of itsrunmethod. Then construct an instance of this subclass and callstarton that instance directly.
ExampleΒΆ
In the following example, the main thread, ThreadDemo, calls the child thread, NewThread, using run. This causes the child thread to run to completion before the rest of the main thread is executed, so that βChild thread activityβ is printed before βMain thread activityβ.
public class ThreadDemo {
public static void main(String args[]) {
NewThread runnable = new NewThread();
runnable.run(); // Call to 'run' does not start a separate thread
System.out.println("Main thread activity.");
}
}
class NewThread extends Thread {
public void run() {
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Child thread activity.");
}
}
To enable the two threads to run concurrently, create the child thread and call start, as shown below. This causes the main thread to continue while the child thread is waiting, so that βMain thread activityβ is printed before βChild thread activityβ.
public class ThreadDemo {
public static void main(String args[]) {
NewThread runnable = new NewThread();
runnable.start(); // Call 'start' method
System.out.println("Main thread activity.");
}
}
ReferencesΒΆ
The Java Tutorials: Defining and Starting a Thread.
Common Weakness Enumeration: CWE-572.