public function DatabaseLockBackend::lockMayBeAvailable

public DatabaseLockBackend::lockMayBeAvailable($name)

Checks if a lock is available for acquiring.

Parameters

string $name: Lock to acquire.

Return value

bool

Overrides LockBackendInterface::lockMayBeAvailable

File

core/lib/Drupal/Core/Lock/DatabaseLockBackend.php, line 108

Class

DatabaseLockBackend
Defines the database lock backend. This is the default backend in Drupal.

Namespace

Drupal\Core\Lock

Code

public function lockMayBeAvailable($name) {
  try {
    $lock = $this->database->query('SELECT expire, value FROM {semaphore} WHERE name = :name', array(':name' => $name))->fetchAssoc();
  }
  catch (\Exception $e) {
    $this->catchException($e);
    // If the table does not exist yet then the lock may be available.
    $lock = FALSE;
  }
  if (!$lock) {
    return TRUE;
  }
  $expire = (float) $lock['expire'];
  $now = microtime(TRUE);
  if ($now > $expire) {
    // We check two conditions to prevent a race condition where another
    // request acquired the lock and set a new expire time. We add a small
    // number to $expire to avoid errors with float to string conversion.
    return (bool) $this->database->delete('semaphore')
      ->condition('name', $name)
      ->condition('value', $lock['value'])
      ->condition('expire', 0.0001 + $expire, '<=')
      ->execute();
  }
  return FALSE;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Lock!DatabaseLockBackend.php/function/DatabaseLockBackend::lockMayBeAvailable/8.1.x