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.