M4ks
M4ks

Reputation: 12024

How to deal with infinite Future in Scala/Akka?

My problem is - I use Scala and Akka - one of the jobs is to use an external API through third party SDK. The problem is I have no control over this SDK and, well, I should expect anything to happen inside, even infinite loop.

I "solved" the problem like this

Await.result( Future { sdk.makeSomeCall()}, 1.minute)

so my code won't block forever. However, I started to test this by stubbing makeSomeCall() with simple Thread.sleep() - and found that Await.result does not actually kill a future, because the test execution continues for around 1.minute and changes with this parameter. I debugged a bit and found, that actually, Await.result returns, however threads continue in the background, waiting for Thread.sleep to finish.

I assume that my code just 'detach' from current Future and let it execute in its given thread - this may quickly lead to some starvation in production code.

Question is simple - how to make it proper - it means that after the timeout passes the new thread/Future will be terminated and all resources allocated by this code will be freed (I assume that SDK may make some mess, but this is not an issue now)

Upvotes: 3

Views: 988

Answers (2)

Ignacio Blasco
Ignacio Blasco

Reputation: 51

Probably you should look to implementation of CancellableFutures or InterruptibleFutures. Here is a gist from VictorKlang with an implementation

Upvotes: 2

Gregor Raýman
Gregor Raýman

Reputation: 3081

I think that you are right in your assumption that Await.result does not "kill" the future. The await limits just how long the waiting code waits, it does not limit the code providing the future with the result at all.

This would not be reasonable in general, since there can be many places in the program that await the result of the same future.

What you could do is to the start the 3rd party code in a thread and wait for the thread to complete in a time limit. If the thread does not finish in the allocated time, you would then kill the thread. You could wrap this logic into a Promise and return either a success, when the 3rd party code finishes on time, or a time-out failure when you had to kill the thread.

Upvotes: 2

Related Questions