package ericminio;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;

public class SynchronizationTest {

    Step one = new Spy();
    Step two = new Spy();
    Workflow workflow = new Workflow(one, two);

    @Test
    public void isNeeded() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> workflow.execute());
        workflow.execute();
        future.get();

        assertThat(Spy.firstCaller, not(equalTo(Spy.secondCaller)));
    }

    @Test
    public void works() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> workflow.executeSynchronously());
        workflow.executeSynchronously();
        future.get();

        assertThat(Spy.firstCaller, equalTo(Spy.secondCaller));
    }

    static class Spy implements Step {

        public static int firstCaller;
        public static int secondCaller;

        public Spy() {
            firstCaller = -1;
            secondCaller = -1;
        }

        @Override
        public void execute() {
            if (firstCaller == -1) {
                firstCaller = Thread.currentThread().hashCode();
            }
            else {
                if (secondCaller == -1) {
                    secondCaller = Thread.currentThread().hashCode();
                }
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

@@ -441,37 +441,40 @@
 leFuture%3CVoid%3E f
-uture
+irstCall
  = CompletableFu
@@ -513,32 +513,102 @@
 cute());%0A       
+ CompletableFuture%3CVoid%3E secondCall = CompletableFuture.runAsync(() -%3E
  workflow.execut
@@ -610,16 +610,17 @@
 xecute()
+)
 ;%0A      
@@ -614,37 +614,66 @@
 te());%0A        f
-uture
+irstCall.get();%0A        secondCall
 .get();%0A%0A       
@@ -827,21 +827,24 @@
 %3CVoid%3E f
-uture
+irstCall
  = Compl
@@ -912,16 +912,86 @@
 %0A       
+ CompletableFuture%3CVoid%3E secondCall = CompletableFuture.runAsync(() -%3E
  workflo
@@ -1014,16 +1014,17 @@
 nously()
+)
 ;%0A      
@@ -1026,21 +1026,50 @@
        f
-uture
+irstCall.get();%0A        secondCall
 .get();%0A
@@ -1733,16 +1733,17 @@
 sleep(10
+0
 );%0A     

increase beauty with symmetry