When Java8 uses referential transparency

872 views Asked by At

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?

1

There are 1 answers

1
lily On BEST ANSWER

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 , the definition of referential transparency given is

A property of a function whereby an expression can be replaced by its (evaluated) value without affecting the meaning of the program.

You can tell that triple is not referentially transparent because a call to e.g. triple(2) is not equivalent to 6, since just evaluating 6 will not print anything or sleep, while triple(2) will also print 2 to the console and sleep for a second. Since replacing triple(2) by 6 would affect the meaning of the program by removing the printing and sleeping, triple is not referentially transparent.