Alternative to Kotlin Coroutines in Java?

Viewed 2061

Is there an alternative to Kotlin Coroutines in Java? I have Kotlin code in which I want to perform facial recognition on one dispatcher, while updating the bounding boxes on the other. I tried to automatically convert the code to Java, but the coroutines part was not converted.

The code is something like this:

withContext( Dispatchers.Default ) {
    //perform face recognition
}

withContext( Dispatchers.Main ) {
    boundingBoxOverlay.faceBoundingBoxes = predictions
    boundingBoxOverlay.invalidate()
    isProcessing.set(false)
}
4 Answers

For the most part...you can't.

Kotlin coroutines rely on transformations performed by the compiler recognizing suspend function calls and handling them specially, tracking their state and resuming them correctly. The Java compiler doesn't do this.

This, unfortunately, means you'll probably end up needing to substantially restructure your code to something callback-based. The best way to do that is going to depend on what you're doing.

Perhaps you can use an ExecutorService to implement concurrent behaviour. The following could help, but the exact solution would depend on how you use the methods too. The withContext() will run both methods concurrently and wait for both of them to finish.

final ExecutorService executorService = Executors.newFixedThreadPool(2);

public final void withContext(){
 final Future<?> futureFacial = this.executorService.submit(this::withContextFacial);
 final Future<?> futureBounding = this.executorService.submit(this::withContextBoundingBoxes);
 futureFacial.get();
 futureBounding.get();

}
private final withContextFacial( ) {
    //perform face recognition }

private final withContextBoundingBoxes() {
    boundingBoxOverlay.faceBoundingBoxes = predictions
    boundingBoxOverlay.invalidate()
    isProcessing.set(false) }

What is important to note is that Kotlin has language level support for coroutines while Java doesn't. That means that you have to workaround the issue and model the solution in another way. There are multiple solutions to this even if one considers Java SRE solutions: Threads, ExecutorService, ForkJoin. And then multiple libraries and approaches outside JRE such as the Actor model or reactive programming.

for run concurrently to constantly update. you can use a service in java a service might continue running for some time, even after the user switches to another application. Click here!

You could write your coroutines, than decompile code and use java-class for coroutine, but it seems to be so non-flexible approach, also you should deal with continuations.

In case of java - just use RXJava instead of coroutines, it is well known approach for concurrency

Related