Enforcing mutual exclusion in Apex

I have an Apex class that calls out to a web service. The webservice doesn’t allow multiple requests at the same time. I have an update trigger on Account that does the callout. So, if multiple users are managing accounts and do saves at more or less the same time, I’m getting errors from the webservice.

Is there a way to enforce mutual exclusion on critical code sections in Apex?


We had a similar issue, and settled on a “callout queue”. Basically a custom object that contains all the information your callout needs (endpoint, body, GET/PUT/POST, etc). Then there’s scheduled apex that grabs the next item on the queue and does what it needs to.

If you need to react to data returned from the endpoint, your custom object can contain the name of a static method made to handle returned data. The static method is served up via a factory class.

(We were more worried about endpoint downtime or communication issues, and our queue was built to ensure that every callout was eventually made, in order, but the queue will serve your purposes equally well.)

Source : Link , Question Author : rael_kid , Answer Author : Matt Welch

Leave a Comment