Skip to content

Commit 7bc38cb

Browse files
committed
Support blocking with: scalaFuture.toJava.toCompletableFuture
I believe this implements the somewhat reluctant consensus reached in #43. Go with the flow by allowing people to block using the standard Java 8 idiom of `toCompletableFuture.get`. I've added a comment and a test to caution that calling `toCompletableFuture.complete(value)` does *not* effect the underlying Promise. Fixes #43
1 parent 416fe31 commit 7bc38cb

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/main/scala/scala/concurrent/java8/FutureConvertersImpl.scala

+9-2
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,15 @@ object FuturesConvertersImpl {
6666
cf
6767
}
6868

69-
override def toCompletableFuture(): CompletableFuture[T] =
70-
throw new UnsupportedOperationException("this CompletionStage represents a read-only Scala Future")
69+
/**
70+
* @inheritdoc
71+
*
72+
* WARNING: completing the result of this method will not complete the underlying
73+
* Scala Future or Promise.
74+
*/
75+
override def toCompletableFuture(): CompletableFuture[T] = {
76+
this // TODO or maybe `thenApply(JF.identity())`
77+
}
7178

7279
override def toString: String = super[CompletableFuture].toString
7380
}

src/test/java/scala/compat/java8/FutureConvertersTest.java

+23
Original file line numberDiff line numberDiff line change
@@ -318,4 +318,27 @@ public void testToJavaExceptionally() throws InterruptedException,
318318
latch.countDown();
319319
assertEquals("Hello", second.toCompletableFuture().get());
320320
}
321+
322+
@Test
323+
public void testToJavaToCompletableFuture() throws ExecutionException, InterruptedException {
324+
final Promise<String> p = promise();
325+
final CompletionStage<String> cs = toJava(p.future());
326+
CompletableFuture<String> cf = cs.toCompletableFuture();
327+
assertEquals("notyet", cf.getNow("notyet"));
328+
p.success("done");
329+
assertEquals("done", cf.get());
330+
}
331+
332+
@Test
333+
public void testToJavaToCompletableFutureDoesNotMutateUnderlyingPromise() throws ExecutionException, InterruptedException {
334+
final Promise<String> p = promise();
335+
Future<String> sf = p.future();
336+
final CompletionStage<String> cs = toJava(sf);
337+
CompletableFuture<String> cf = cs.toCompletableFuture();
338+
assertEquals("notyet", cf.getNow("notyet"));
339+
cf.complete("done");
340+
assertEquals("done", cf.get());
341+
assertFalse(sf.isCompleted());
342+
assertFalse(p.isCompleted());
343+
}
321344
}

0 commit comments

Comments
 (0)