Skip to content

Commit eaa5be3

Browse files
t-rutten7h3kk1d
andcommitted
Parallel computation in applicatives
Co-authored-by: Alexander Bandukwala <[email protected]>
1 parent 1271ab7 commit eaa5be3

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/test/java/com/jnape/palatable/lambdakoans/AboutApplicatives.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,12 @@
99
import com.jnape.palatable.lambda.functions.builtin.fn4.LiftA3;
1010
import com.jnape.palatable.lambda.functor.Applicative;
1111
import com.jnape.palatable.lambda.functor.builtin.Lazy;
12+
import com.jnape.palatable.lambda.io.IO;
1213
import com.jnape.palatable.lambda.traversable.LambdaIterable;
1314
import org.junit.Test;
1415

16+
import java.util.concurrent.ExecutionException;
17+
import java.util.concurrent.Executors;
1518
import java.util.concurrent.atomic.AtomicInteger;
1619

1720
import 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

Comments
 (0)