Why do variables passed to runnable need to be final?

Because that’s what the language specification says. According to Guy Steele, the rationale behind this choice is that programmers would expect the declaration int x = 0 in a method to result in stack-allocated storage, but if you can return a new myRun() from the method (or otherwise let a myRun persist past the function’s return) and you can modify it afterwards, then x has to be heap-allocated instead to have the semantics you’d expect.

They could have done that, and in fact other languages have done it that way. But the Java designers decided instead to require that you mark x as final to avoid requiring implementations to heap-allocate what looks like stack-allocated storage.

(I should note: this isn’t specific to Runnable. It applies to any anonymous inner class.)

Leave a Comment