Technology

6 Mistakes To Avoid if You Work With Scala Futures

Code with sneaky api 🙁

He goes through his own code multiple times and couldn’t find an opportunity. Then he started to look more closely at a certain library API which he had overlooked several times before.

This is the seemingly innocent looking method signature of the suspicious library..

def executeOperation(): Future[Boolean]

“Ahh! It’s just an asynchronous code!”, he thinks, “Even if it is in the main api flow, no issues, because it is just a separate Future like that cache service method”. Or is it? He wants to make sure.

Using his beloved Intellij’s Command+Click feature, he tries to dig into the code.

He ends up finding that the method is doing some heavy CPU operation before scheduling some other future and returning it!!!

Sneaky API 🙁

After some serious pondering, George came to an epiphany that you can’t judge a method by its return type.

Just by looking at the method signature, you can’t really tell

1. which part of the method will run in current thread,
2. which parts are scheduled as future operation or
3. it is just a sync operation simply lifted using Future.successful(something)

He is happy about his realisation and goes around telling about it to his colleagues. But Martha ask him what is the fix in the end?

Then he goes pondering again and came up with this fix: Don’t trust the library and just wrap it into our own Future probably with its own dedicated ExecutionContext.

Fix for the sneaky api 🙂

Related Articles

Back to top button