9
9
import com .jnape .palatable .lambda .functions .builtin .fn4 .LiftA3 ;
10
10
import com .jnape .palatable .lambda .functor .Applicative ;
11
11
import com .jnape .palatable .lambda .functor .builtin .Lazy ;
12
+ import com .jnape .palatable .lambda .io .IO ;
12
13
import com .jnape .palatable .lambda .traversable .LambdaIterable ;
13
14
import org .junit .Test ;
14
15
16
+ import java .util .concurrent .ExecutionException ;
17
+ import java .util .concurrent .Executors ;
15
18
import java .util .concurrent .atomic .AtomicInteger ;
16
19
17
20
import static com .jnape .palatable .lambda .adt .Either .left ;
@@ -117,4 +120,37 @@ public void functionIsApplicative() {
117
120
Fn1 <String , String > transformAndCut = LiftA3 .liftA3 (cutString , toUpper , findStart , findEnd );
118
121
assertThat (transformAndCut .apply ("hellojava world" ), equalTo ("JAVA" ));
119
122
}
123
+
124
+ @ Test
125
+ public void applicativeRepresentsParallelism () throws ExecutionException , InterruptedException {
126
+ IO <Integer > foo = IO .io (() -> {
127
+ Thread .sleep (2_000 );
128
+ return 14 ;
129
+ });
130
+
131
+ IO <Integer > bar = IO .io (() -> {
132
+ Thread .sleep (2_000 );
133
+ return 28 ;
134
+ });
135
+
136
+ IO <Integer > applicativeInIo = LiftA2 .liftA2 (Integer ::sum , foo , bar );
137
+
138
+ long singleThreadStart = System .currentTimeMillis ();
139
+
140
+ applicativeInIo
141
+ .flatMap (result -> IO .io (() -> assertThat (result , equalTo (42 ))))
142
+ .unsafePerformIO ();
143
+
144
+ System .out .printf ("Single thread execution took %d seconds%n" , (System .currentTimeMillis () - singleThreadStart ) / 1000 );
145
+
146
+ // If we have multiple threads available, function evaluation is done in parallel
147
+ long multipleThreadStart = System .currentTimeMillis ();
148
+
149
+ applicativeInIo
150
+ .flatMap (result -> IO .io (() -> assertThat (result , equalTo (42 ))))
151
+ .unsafePerformAsyncIO (Executors .newFixedThreadPool (2 ))
152
+ .get ();
153
+
154
+ System .out .printf ("Single thread execution took %d seconds%n" , (System .currentTimeMillis () - multipleThreadStart ) / 1000 );
155
+ }
120
156
}
0 commit comments