Skip to content

sharedCache.getMutex

Signature: sharedCache.getMutex(mutexId, timeout*, lifespan*, namespace*, global*, persist*)

Returns: Boolean result - true if the mutex was successfully obtained

Claim the mutex associated with the mutexId.

When no namespace is specified, the mutex is only accessible from inside the channel in which the mutexId is claimed. When a namespace is specified, the mutex is accessible to all channels in the same zone as the channel in which it is claimed. When global is set to true, the mutex is accessible to all channels across all zones.

Note

When global is set to true and no namespace is supplied, one shared global namespace is used, which every channel in every zone can read and write. Supply a namespace to keep global values apart.

Note

namespace is optional. When not specified, {channel ID} scopes the value to the channel running the script, so no other channel can see it.

Note

persist is optional. When not specified, {system default} is the Default Storage setting on the System Config page under Shared Cache Settings.

Parameters

Type Name Description Default
String mutexId a unique string that identifies the mutex to claim
Long timeout* (optional) the amount of time in milliseconds you are willing to wait in order to obtain the mutex 30000
Long lifespan* (optional) the amount of time in milliseconds that you can hold onto the mutex after which it will be available for others to claim 20000
String namespace* (optional) a unique string used to limit the scope of the mutex {channel ID}
Boolean global* (optional) specifies whether the mutex is stored in the global cache false
Boolean persist* (optional) specifies whether or not the mutex is stored in the database {system default}

Example

// Serialize a check-then-act on a shared value so two messages processing at the
// same time cannot both refresh the cached token.
if (sharedCache.getMutex("token-refresh", 15000, 50000)) {
   try {
      // While this block runs, any other channel claiming the same mutexId waits
      // here until the mutex is released or its lifespan expires.
      if (!sharedCache.checkValueExists("authToken")) {
         // Only the first message through refreshes the token; the rest reuse it.
         sharedCache.setValue("authToken", "cached-token-value", 3600);
      }
   } finally {
      // Always release in a finally block so the mutex is freed even if the work throws.
      sharedCache.releaseMutex("token-refresh");
   }
} else {
   qie.warn("Timed out waiting for the token-refresh mutex");
}