5

The short question is - do future methods run in parallel, or sequentially?

I am wondering if race is possible in Salesforce. Let's say We've got some singleton class S that we want to call from some future method f, which is called few times in a loop like:

while(x)
    f() // this future method calls our singleton S

The typical scenario here is that it is possible to break the singleton when it's not thread-safe and instantiate it more than once. It it possible in Apex?

2 Answers 2

5

Future methods run in an entirely new process (that could easily be on a different server than the original request) so all the code is reloaded and re-initialised. In general, the only state that carries over is data that is saved in the database - so state cached in singletons will be lost. (Batchables have an additional Database.Stateful marker available that allows state in non-static fields to be carried over between batches.)

Further, there are no constructs in Apex to create additional threads within a process. So you can rely on your code only ever being executed by a single thread.

This Asynchronous Processing in Force.com PDF is worth a read to get a sense for how asynchronous processing is handled by the platform. Future requests can be processed in parallel but a separate process will be used for each one. As Bart notes in his comment SOQL's for update is a mechanism that can be used to ensure sequential access to the database.

1

I just try to do few things with @future annotation. When you reference static field in the singleton class from the @future method - each method will run in that's own context and changes will be separate one from other.

But! When you call @future method and it makes some database updates - there are interest situation. Loop go 50 times through the numeric field and increment it by one. Than result was write to the debug log. Here are the output: 1 1 1 2 2 2 2 ........ 5 3 8.

So if you use @future annotation with some singleton class you may break your development model.

1
  • 1
    Sure, that's what for update clause is. Oct 23, 2015 at 9:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .