Non blocking interop with JVM like Deffered.await()

Hello, I need a help with some interop with Java 8.

Mine application consist of 3 parts.

  1. kotlin part that execute REST calls with suspend function for text recognition that should return Transcription. REST response could be immediate or could take 5-20 min, in this situation i’m delay for such time as I need response with Transcription.

  2. Java part should return Transcription from step 1 to internal index engine. I’m using CompletableFuture.get() but as I see it block a Thread.

  3. For those step used shared pool that catch incoming document, init it (step 2 → execute step 1) and index.

Is it possible some how interop step 2 like Deffered.await() to non block thread from thread pool?

Thanks.

Probably you need kotlinx.coroutines/integration/kotlinx-coroutines-jdk8 at master · Kotlin/kotlinx.coroutines · GitHub.

1 Like

Thanks.
I’m already using it, and it is wrap with CompletableFeature, which get() method is blocking, if I understand it correct.

In Java you must use callbacks to write async non-blocking code.

Try CompletableFuture.thenAccept instead of calling get. The supplied callback will run when the task completes without blocking any threads. You can control the callback thread with thenAcceptAsync. The code that uses the result goes in the callback not after the call to thenAccept, which will return immediately without waiting.

I suggest referring to guide, here’s an example : Java CompletableFuture Tutorial with Examples

1 Like

It is not possible, as I have no access to change interface method. And this method is

Optional getText() - so I want implement it and make Thread non block.

Thanks.

All Java methods block their thread until they return. There is no way around this. To get a result without blocking the thread you must use a callback parameter, so the method can return immediately, and the callback can be stored and invoked later.

Even in Kotlin with coroutines, the suspend modifier is rewriting the code to use callbacks (it adds a callback parameter to the signature).

If you have a synchronous Java API that you are implementing, then it will have to block the thread. The standard way to implement such an API with coroutines is runBlocking. Be careful to ensure that runBlocking is not called from a coroutine dispatcher to avoid deadlocks.

1 Like

Thanks!