Standard Analyses

SemmleCode Professional comes with a wide range of pre-packaged analyses, from architectural properties and metrics, to statement-level checks for likely bugs and violations of best practice.


Start of Thread in Constructor

This query finds constructors that start a thread. If the class is ever extended, the thread will be started before the subclass constructor is started, which may not be intended.

Take the following example program:

    class Super {
        public Super() {
            new Thread() {
                public void run() {
                    System.out.println("here");
                }
            }.start();
        }
    }

    class Test extends Super {
        public Test() {
            System.out.println("there");
        }

        public static void main(String[] args) {
            new Test();
        }
    }

Since the constructor of Test implicitly invokes the constructor of Super, the thread created in that constructor will be started before the print statement in Test's constructor is executed, hence the program might print here and there in any order.

How to Interpret the Query Results

The query flags all such constructors and provides a list of all detected occurrences in the results view.

How to Address the Query Results

Refactor the code to avoid starting threads in constructors.

Source Code
import default

from MethodAccess m
where m.getMethod().getDeclaringType().hasQualifiedName("java.lang", "Thread") and 
      m.getMethod().getName() = "start" and 
      m.getEnclosingCallable() instanceof Constructor
select m, "Thread started in constructor"
References