99import com .jnape .palatable .lambda .functions .builtin .fn4 .LiftA3 ;
1010import com .jnape .palatable .lambda .functor .Applicative ;
1111import com .jnape .palatable .lambda .functor .builtin .Lazy ;
12+ import com .jnape .palatable .lambda .io .IO ;
1213import com .jnape .palatable .lambda .traversable .LambdaIterable ;
1314import org .junit .Test ;
1415
16+ import java .util .concurrent .ExecutionException ;
17+ import java .util .concurrent .Executors ;
1518import java .util .concurrent .atomic .AtomicInteger ;
1619
1720import static com .jnape .palatable .lambda .adt .Either .left ;
@@ -117,4 +120,37 @@ public void functionIsApplicative() {
117120 Fn1 <String , String > transformAndCut = LiftA3 .liftA3 (cutString , toUpper , findStart , findEnd );
118121 assertThat (transformAndCut .apply ("hellojava world" ), equalTo ("JAVA" ));
119122 }
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+ }
120156}
0 commit comments