Though the below snippet works fine, I have couple of questions to better understand on exactly what is happening behind.
Say I have a code like below
As you have noticed from the above code, parameter "param" is being passed to execute method and in turn that is being used inside run() method of inline anonymous implementation of Runnable.
If we keep inline declaration aside, technically this should have been technically equivalent to
and in ExecutorService
So, if we compare the first and second ExecutorService, are the steps to set the param and making it available with in run() method of and others are happening behind the scenes by compiler. If Yes, how would compiler determine, if that should use a setter or a constructor to make sure the param is available to Runnable instance.
Also, is there any prominence in declaring the param as "final" with respect to this kind of method passing.
These two methods are not equivalent.
Look at this code:
In this code Runnable 1 and Runnable 2 are objects of the class MyRunnable.
Both of them have each own, independent copy of 'param', and can freely modify it (can modify own copies of param, but not param from the execute method ).
Runnable 3 and Runnable 4 are objects of the anonymous Runnable class,
they both use the same param variable from the enclosing class (method).
Runnables 3 and 4 do not compile because param is declared final (final variables cannot be modified).
Param must be declared final, because anonymous classes can only reference local variables and parameters from the enclosing class or method that are declared final.
In other words, anonymous inner classes cannot modify variables and parameters of the enclosing class/method, can only read them.
If you remove instructions that modify param variable, this code compiles fine.
This is a requirement of Java language semantics - final clause makes that "shared" parameter immutable and therefore thread-safe,
so developer don't have to bother with synchronization in inner classes.