We note that java 8 uses Referential Transparency :
I test many codes to detect this RT,such as:
public class ReferentialTransparency {
public static int triple(int number) {
System.out.println(number);
try {
Thread.sleep(500);
} catch (Exception e) {
}
return number* 3;
}
public static void main(String[] args) {
List<Integer> vals=Arrays.asList(1,2,3,4,3);
System.out.println(vals.parallelStream()
.mapToInt(ReferentialTransparency::triple)
.sum());
}
}
CONSOLE :
3
4
2
1
3
39
I note that Java 8 runs triple methods even there is an element which is appeared two times which is 3
.
My question ,as Istvan interprets,is :
Why doesn't the compiler optimize out the repeated call to triple(3) if triple is referentially transparent?
Your
triple
method is not referentially transparent, since it both prints something to the console and sleeps. Neither of these actions is referentially transparent. In fact, it's quite difficult to detect (from within your code) whether the compiler optimizes out any calls to a referentially transparent function, since if you add a print statement to detect it, then by definition your function is no longer referentially transparent.Note that in the link you gave to referential-transparency, the definition of referential transparency given is
You can tell that
triple
is not referentially transparent because a call to e.g.triple(2)
is not equivalent to6
, since just evaluating6
will not print anything or sleep, whiletriple(2)
will also print 2 to the console and sleep for a second. Since replacingtriple(2)
by6
would affect the meaning of the program by removing the printing and sleeping,triple
is not referentially transparent.