release example

$this->releaseThreadLock();
    // Update the {comment_entity_statistics} table prior to executing the hook.     \Drupal::service('comment.statistics')->update($this);
  }

  /** * Release the lock acquired for the thread in preSave(). */
  protected function releaseThreadLock() {
    if ($this->threadLock) {
      \Drupal::lock()->release($this->threadLock);
      $this->threadLock = '';
    }
  }

  /** * {@inheritdoc} */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage$entities);

    $child_cids = $storage->getChildCids($entities);
    
$this->fileSystem->move($temp_file_path$file_uri, FileSystemInterface::EXISTS_ERROR);
    }
    catch (FileException $e) {
      throw new HttpException(500, 'Temporary file could not be moved to file location');
    }

    // Second step of the validation on the file object itself now.     $this->resourceValidate($file);

    $file->save();

    $this->lock->release($lock_id);

    // 201 Created responses return the newly created entity in the response     // body. These responses are not cacheable, so we add no cacheability     // metadata here.     return new ModifiedResourceResponse($file, 201);
  }

  /** * Streams file upload data to temporary file and moves to file destination. * * @return string * The temp file path. * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * Thrown when input data cannot be read, the temporary file cannot be * opened, or the temporary file cannot be written. */

        $key = new Key('key', 1);
        $store = $this->createMock(PersistingStoreInterface::class);
        $semaphore = new Semaphore($key$store);

        $store
            ->expects($this->once())
            ->method('delete')
            ->with($key)
        ;

        $semaphore->release();
    }

    public function testReleaseWhenItFails()
    {
        $key = new Key('key', 1);
        $store = $this->createMock(PersistingStoreInterface::class);
        $semaphore = new Semaphore($key$store);

        $store
            ->expects($this->once())
            ->method('delete')
            
private ?LockInterface $lock;
    private StorageInterface $storage;
    private string $id;

    public function reset(): void
    {
        try {
            $this->lock?->acquire(true);

            $this->storage->delete($this->id);
        } finally {
            $this->lock?->release();
        }
    }
}
return new RateLimit($availableTokens$window->getRetryAfter(), false, $this->limit);
            }

            $window->add($tokens);

            if (0 < $tokens) {
                $this->storage->save($window);
            }

            return new RateLimit($this->getAvailableTokens($window->getHitCount())$window->getRetryAfter(), true, $this->limit);
        } finally {
            $this->lock?->release();
        }
    }

    private function getAvailableTokens(int $hitCount): int
    {
        return $this->limit - $hitCount;
    }
}
$queue_worker_manager = $this->prophesize('Drupal\Core\Queue\QueueWorkerManagerInterface');
    $state = $this->prophesize('Drupal\Core\State\StateInterface');
    $account_switcher = $this->prophesize('Drupal\Core\Session\AccountSwitcherInterface');
    $queueConfig = [
      'suspendMaximumWait' => 30.0,
    ];

    // Create a lock that will always fail when attempting to acquire; we're     // only interested in testing ::processQueues(), not the other stuff.     $lock_backend = $this->prophesize('Drupal\Core\Lock\LockBackendInterface');
    $lock_backend->acquire('cron', Argument::cetera())->willReturn(TRUE);
    $lock_backend->release('cron')->shouldBeCalled();

    // Create a queue worker definition for testing purposes.     $queue_worker = $this->randomMachineName();
    $queue_worker_definition = [
      'id' => $queue_worker,
      'cron' => [
        'time' => &$this->claimTime,
      ],
    ];

    // Create a queue instance for this queue worker.


    try {
      $this->fileSystem->move($temp_file_path$file_uri, FileSystemInterface::EXISTS_ERROR);
    }
    catch (FileException $e) {
      throw new HttpException(500, 'Temporary file could not be moved to file location');
    }

    $file->save();

    $this->lock->release($lock_id);

    return new JsonResponse([
      'url' => $file->createFileUrl(),
      'uuid' => $file->uuid(),
      'entity_type' => $file->getEntityTypeId(),
    ], 201);
  }

  /** * Access check based on whether image upload is enabled or not. * * @param \Drupal\editor\Entity\Editor $editor * The text editor for which an image upload is occurring. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */
    $violations = $file->validate();

    // Remove violations of inaccessible fields as they cannot stem from our     // changes.     $violations->filterByFieldAccess();
    if ($violations->count() > 0) {
      return $violations;
    }

    $file->save();

    $this->lock->release($lock_id);

    return $file;
  }

  /** * Validates and extracts the filename from the Content-Disposition header. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * * @return string * The filename extracted from the header. * * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException * Thrown when the 'Content-Disposition' request header is invalid. */
if ($this->memoryLimit !== '-1') {
            $workerDispatcher->addSubscriber(new StopWorkerOnMemoryLimitListener(
                MemorySizeCalculator::convertToBytes($this->memoryLimit)
            ));
        }

        $worker = new Worker([$this->defaultTransportName => $receiver]$this->bus, $workerDispatcher);

        $worker->run(['sleep' => 50]);

        $consumerLock->release();

        return new JsonResponse(['handledMessages' => $listener->getHandledMessages()]);
    }
}
$checkpoint = new Checkpoint('dummy');

        $this->assertTrue($checkpoint->acquire($now));
        $this->assertSame($now$checkpoint->time());
        $this->assertSame(-1, $checkpoint->index());

        $checkpoint->save($later, 7);

        $this->assertSame($later$checkpoint->time());
        $this->assertSame(7, $checkpoint->index());

        $checkpoint->release($later, null);
    }

    public function testWithStateInitStateOnFirstAcquiring()
    {
        $checkpoint = new Checkpoint('cache', new NoLock()$cache = new ArrayAdapter());
        $now = new \DateTimeImmutable('2020-02-20 20:20:20Z');

        $this->assertTrue($checkpoint->acquire($now));
        $this->assertEquals($now$checkpoint->time());
        $this->assertEquals(-1, $checkpoint->index());
        $this->assertEquals([$now, -1, $now]$cache->get('cache', fn () => []));
    }
// Set and delete operations invalidate the cache item. Try to also load       // an eventually invalidated cache entry, only update an invalidated cache       // entry if the creation date did not change as this could result in an       // inconsistent cache.       if ($cache = $this->cache->get($cid$this->cacheInvalidated)) {
        if ($this->cacheInvalidated && $cache->created != $this->cacheCreated) {
          // We have invalidated the cache in this request and got a different           // cache entry. Do not attempt to overwrite data that might have been           // changed in a different request. We'll let the cache rebuild in           // later requests.           $this->cache->delete($cid);
          $this->lock->release($lock_name);
          return;
        }
        $data = array_merge($cache->data, $data);
      }
      elseif ($this->cacheCreated) {
        // Getting here indicates that there was a cache entry at the         // beginning of the request, but now it's gone (some other process         // must have cleared it). We back out to prevent corrupting the cache         // with incomplete data, since we won't be able to properly merge         // the existing cache data from earlier with the new data.         // A future request will properly hydrate the cache from scratch.
if ($cached = $this->cache->get($this->cid)) {
        // Use array merge instead of union so that filled in values in $data         // overwrite empty values in the current cache.         $data = array_merge($cached->data, $data);
      }
      else {
        $registry = $this->initializeRegistry();
        $data = array_merge($registry$data);
      }
      $this->cache->set($this->cid, $data, Cache::PERMANENT, $this->tags);
      if ($lock) {
        $this->lock->release($lock_name);
      }
    }
  }

}
protected function configure(): void
    {
        $this->setName('foo:lock');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if (!$this->lock()) {
            return 1;
        }

        $this->release();

        return 2;
    }
}


  /** * Finishes the batch. * * @param array|\ArrayAccess $context * The batch context. */
  protected function finish(&$context) {
    $this->eventDispatcher->dispatch(new ConfigImporterEvent($this), ConfigEvents::IMPORT);
    // The import is now complete.     $this->lock->release(static::LOCK_NAME);
    $this->reset();
    $context['message'] = t('Finalizing configuration synchronization.');
    $context['finished'] = 1;
  }

  /** * Gets the next extension operation to perform. * * Uninstalls are processed first with themes coming before modules. Then * installs are processed with modules coming before themes. This order is * necessary because themes can depend on modules. * * @return array|bool * An array containing the next operation and extension name to perform it * on. If there is nothing left to do returns FALSE; */
// ALTER is the final step to alter all the existing routes. We cannot stop     // people from adding new routes here, but we define two separate steps to     // make it clear.     $this->dispatcher->dispatch(new RouteBuildEvent($collection), RoutingEvents::ALTER);

    $this->checkProvider->setChecks($collection);

    $this->dumper->addRoutes($collection);
    $this->dumper->dump();

    $this->lock->release('router_rebuild');
    $this->dispatcher->dispatch(new Event(), RoutingEvents::FINISHED);
    $this->building = FALSE;

    $this->rebuildNeeded = FALSE;

    return TRUE;
  }

  /** * {@inheritdoc} */
  
Home | Imprint | This part of the site doesn't use cookies.