@@ -150,6 +150,51 @@ This component also provides two useful methods related to expiring locks:
150
150
``getExpiringDate() `` (which returns ``null `` or a ``\DateTimeImmutable ``
151
151
object) and ``isExpired() `` (which returns a boolean).
152
152
153
+ The Owner of The Lock
154
+ ---------------------
155
+
156
+ Locks that are acquired for the first time are owned[1]_ by the ``Lock `` instance that acquired
157
+ it. If you need to check whether the current ``Lock `` instance is (still) the owner of
158
+ a lock, you can use the ``isAcquired() `` method::
159
+
160
+ if ($lock->isAcquired()) {
161
+ // We (still) own the lock
162
+ }
163
+
164
+ Because of the fact that some lock stores have expiring locks (as seen and explained
165
+ above), it is possible for an instance to lose the lock it acquired automatically::
166
+
167
+ // If we cannot acquire ourselves, it means some other process is already working on it
168
+ if (!$lock->acquire()) {
169
+ return;
170
+ }
171
+
172
+ $this->beginTransaction();
173
+
174
+ // Perform a very long process that might exceed TTL of the lock
175
+
176
+ if ($lock->isAcquired()) {
177
+ // Still all good, no other instance has acquired the lock in the meantime, we're safe
178
+ $this->commit();
179
+ } else {
180
+ // Bummer! Our lock has apparently exceeded TTL and another process has started in
181
+ // the meantime so it's not safe for us to commit.
182
+ $this->rollback();
183
+ throw new \Exception('Process failed');
184
+ }
185
+
186
+ .. caution ::
187
+
188
+ A common pitfall might be to use the ``isAcquired() `` method to check if
189
+ a lock has already been acquired by any process. As you can see in this example
190
+ you have to use ``acquire() `` for this. The ``isAcquired() `` method is used to check
191
+ if the lock has been acquired by the **current process ** only!
192
+
193
+ .. [1 ] Technically, the true owners of the lock are the ones that share the same instance of ``Key ``,
194
+ not ``Lock ``. But from a user perspective, ``Key `` is internal and you will likely only be working
195
+ with the ``Lock `` instance so it's easier to think of the ``Lock `` instance as being the one that
196
+ is the owner of the lock.
197
+
153
198
Available Stores
154
199
----------------
155
200
0 commit comments