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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With