Direct call to a run() method¶
ID: java/call-to-thread-runKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - reliability - concurrency - external/cwe/cwe-572Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
A direct call of aThread object’srun method does not start a separate thread. The method is executed within the current thread. This is an unusual use becauseThread.run() is normally intended to be called from within a separate thread.
Recommendation¶
To executeRunnable.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, usingrun. 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”.
publicclassThreadDemo{publicstaticvoidmain(Stringargs[]){NewThreadrunnable=newNewThread();runnable.run();// Call to 'run' does not start a separate threadSystem.out.println("Main thread activity.");}}classNewThreadextendsThread{publicvoidrun(){try{Thread.sleep(10000);}catch(InterruptedExceptione){System.out.println("Child interrupted.");}System.out.println("Child thread activity.");}}
To enable the two threads to run concurrently, create the child thread and callstart, 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”.
publicclassThreadDemo{publicstaticvoidmain(Stringargs[]){NewThreadrunnable=newNewThread();runnable.start();// Call 'start' methodSystem.out.println("Main thread activity.");}}
References¶
The Java Tutorials:Defining and Starting a Thread.
SEI CERT Oracle Coding Standard for Java:THI00-J. Do not invoke Thread.run().
Java API Specification:Thread.
Java API Specification:Runnable.
Common Weakness Enumeration:CWE-572.