'(Cache::lock()) -> get() -- Under what conditions does it return false?

I'm looking into using the Cache::lock mechanism with laravel, but something isn't exactly clear to me.

This is the example they use:

$lock = Cache::lock('foo', 10);

if ($lock->get()) {
    // Lock acquired for 10 seconds...

    $lock->release();
}

Now, it's my understanding that under NORMAL conditions, if the lock is still in place when $lock->get() is called, it will wait for the previous lock to be released before continuing on. Is that correct? (that seems like the whole point of a lock to me, so I certainly hope that's correct).

If that is correct, then what would ever make $lock->get() return false? Would it return false if it expects the wait time to be over 10 seconds, or something like that?



Solution 1:[1]

It's not easy to find something in the laravel docs and in the sources about this. What I've been able to gather is that the call to Cache::lock does not acquire it, it seems to only define what is able to be locked.

The calls to get() and block() seem to do the actual acquiring.

My assumptions are as follows:

  • Cache::lock(foo, n) will create a new lock on foo that can be held for a maximum of n seconds
  • $lock->get() will try to acquire it and return false if it was already held by someone else.
  • $lock->block(n) will try to acquire it and block for a maximum of n seconds, if it fails to acquire during this time, it will throw LockTimeoutException

You should test if it actually follows this behavior though as I'm not able to confirm this.


For reference:

Solution 2:[2]

The calls of $lock->get() also do lock. Just try this code

Log::info('checkpoint 2 ' .  $lock->owner() . " - get? " . ($lock->get() ? "true" : "false") );
Log::info('checkpoint 2A ' .  $lock->owner() . " - get? " . ($lock->get() ? "true" : "false") );

It would return

[2022-05-12 22:41:11] production.INFO: checkpoint 2 l5qJhOOORy1nNFHt - get? true
[2022-05-12 22:41:11] production.INFO: checkpoint 2A l5qJhOOORy1nNFHt - get? false

From above result, we can know that the first $lock->get() will get return boolean true, and the second $lock->get() would get return boolean false. It is indicate the $lock->get() also do some locking thread until you do $lock->release() or $lock->forceRelease()

The documentation doesn't mentioned about this and hopefully it would help others.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Yohanim