Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler not catch this error?

Tags:

java

When I call the start method on a dead thread I get the java.lang.IllegalThreadStateException at runtime but the compilation goes fine.

class Foo implements Runnable {

    public void run() {

    }

    public static void main(String [] args) {
        Runnable r = new Foo();
        Thread t = new Thread(r);

        t.start();
        t.start();
    }
}

My question is why does the Java compiler not catch such errors ?

like image 819
user691451 Avatar asked Jun 14 '26 08:06

user691451


2 Answers

Because it's a semantic error. The border between syntactic and semantic errors is fuzzy, but in general catching all semantic errors is impossible (see halting problem) so language designers and compiler writers have to make a tradeoff between protecting the programmer from himself and compiling fast enough.

To catch this particular error, the compiler would need to have knowledge of the threading library's semantics. It doesn't, because threading in Java was designed as part of the library, not as part of the language.

like image 72
Fred Foo Avatar answered Jun 15 '26 23:06

Fred Foo


Because its not a syntax error or a type error. Its a runtime error. This is because the compiler doesn't understand the constraints on how every method works.

Even most code analysers don't pick up this as an error.

However, if you write a simple unit test or run the program, the error will be obvious.

like image 36
Peter Lawrey Avatar answered Jun 15 '26 22:06

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!