If you do not need all the functions of the CompletableFuture (for example, the result chain), you can use this class (Kotlin):
class CompletableFutureCompat<V> : Future<V> { private sealed class Result<out V> { abstract val value: V class Ok<V>(override val value: V) : Result<V>() class Error(val e: Throwable) : Result<Nothing>() { override val value: Nothing get() = throw e } object Cancel : Result<Nothing>() { override val value: Nothing get() = throw CancellationException() } } private val completion = LinkedBlockingQueue<Result<V>>(1) private val result = FutureTask<V> { completion.peek()!!.value } fun completeExceptionally(ex: Throwable): Boolean { val offered = completion.offer(Result.Error(ex)) if (offered) { result.run() } return offered } override fun cancel(mayInterruptIfRunning: Boolean): Boolean { val offered = completion.offer(Result.Cancel) if (offered) { result.cancel(mayInterruptIfRunning) } return offered } fun complete(value: V): Boolean { val offered = completion.offer(Result.Ok(value)) if (offered) { result.run() } return offered } override fun isDone(): Boolean = completion.isNotEmpty() override fun get(): V = result.get() override fun get(timeout: Long, unit: TimeUnit): V = result.get(timeout, unit) override fun isCancelled(): Boolean = completion.peek() == Result.Cancel }
source share