DEV Community

developer-help
developer-help

Posted on

Fallacies of Async programming

Hi Guys,

I want to share another fallacy of async programming where developers often think it is a synchronous program. This situation just happened when I was doing pair programming with one of the team members. There was a an existing code this person has already written and we were debugging why it is not save as well as not throwing exception. In order to make it more clear.

Consider below code snippet which looks simple, ignoring the syntax and just showing async nature stuff.

public class BasicCrudOperations
caller() {
calledMethod(arg1, arg2, arg3);
}

private calledMethod(String a, String b, String c) {
System.out.println("This is my work");
try {
()-> { MongoDB.save(a,b,c);
}

}
} catch(Exception e) {
e.printStackTrace();
}

In the above code caller is calling called method in sync fashion and doing try catch around async lambda expressions. Now developer expects that if something fails exception will occur and being caught in catch block. Essentially this will never happen as call to Mongo save operation happens in separate thread nothing to do with current thread calling calledMethod from caller. This trap will not be visible until we go to production/preprod/testing environment where things go still developer wonder why i am not seeing exception. Make sure you handle such scenarios proactive during reviews.
Happy Coding.

Top comments (0)