Winter 24 – API 59

Block Duplicate Queueable Jobs

This is one of the most exciting innovations in Apex I’ve seen in a while. One of the challenges with queueables is that because they are asynchronous, you can end up with race conditions – conflicts when updating the database. To prevent this you might end up using For Update queries or other techniques to detect conflicts. These, in turn, might result in exceptions due to lock errors. For Update queries and lock errors also cause delays – which can make race conditions more likely to occur.

This new features allows you to create Singleton queueables – you can define a particular condition, or “signature”, that allows only a single queueable with that signature to exist at any given time. For example: you might say that only once instance of Queueable class “foo” can run, or that only one instance of that class for a given user can run. If you ensure that a given resource (database object or field) can only be accessed by a particular signature instance, you can eliminate the possibility of lock errors.

In particular, this feature allows you to avoid having to query against the AsyncApexJob object to determine if there is already an existing Apex Job for a given class and user (see page 239), resulting in a solution that is more reliable and offers improved performance.

When thinking about design patterns for this feature, be sure to also consider the recent addition of including a delay for a queueable. You could, for example, combine those features when building an asynchronous framework – using singleton queueables with delays instead of a scheduler approach (see chapter 7). You could even build solutions without a full asynchronous framework to address the issues described in the blog post https://advancedapex.com/2022/04/09/dynamic-bulkification/.

Comparators and Collators

These new Apex features make it easier to sort lists based on criterias you define. It’s not an extremely common task, but very helpful for those who need it.