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.

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 ms
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 ms
String namespace* (optional) a unique string used to limit the scope of the mutex null
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 false

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");
}