@@ -31,6 +31,7 @@ final class Lock implements LockInterface, LoggerAwareInterface
3131 private $ store ;
3232 private $ key ;
3333 private $ ttl ;
34+ private $ dirty = false ;
3435
3536 /**
3637 * @param Key $key Resource to lock
@@ -52,7 +53,7 @@ public function __construct(Key $key, StoreInterface $store, $ttl = null)
5253 public function __destruct ()
5354 {
5455 try {
55- if ($ this ->isAcquired ()) {
56+ if ($ this ->dirty && $ this -> isAcquired ()) {
5657 $ this ->release ();
5758 }
5859 } catch (\Throwable $ e ) {
@@ -72,6 +73,7 @@ public function acquire($blocking = false)
7273 $ this ->store ->waitAndSave ($ this ->key );
7374 }
7475
76+ $ this ->dirty = true ;
7577 $ this ->logger ->info ('Successfully acquired the "{resource}" lock. ' , array ('resource ' => $ this ->key ));
7678
7779 if ($ this ->ttl ) {
@@ -80,6 +82,7 @@ public function acquire($blocking = false)
8082
8183 return true ;
8284 } catch (LockConflictedException $ e ) {
85+ $ this ->dirty = false ;
8386 $ this ->logger ->warning ('Failed to acquire the "{resource}" lock. Someone else already acquired the lock. ' , array ('resource ' => $ this ->key ));
8487
8588 if ($ blocking ) {
@@ -104,8 +107,10 @@ public function refresh()
104107
105108 try {
106109 $ this ->store ->putOffExpiration ($ this ->key , $ this ->ttl );
110+ $ this ->dirty = true ;
107111 $ this ->logger ->info ('Expiration defined for "{resource}" lock for "{ttl}" seconds. ' , array ('resource ' => $ this ->key , 'ttl ' => $ this ->ttl ));
108112 } catch (LockConflictedException $ e ) {
113+ $ this ->dirty = false ;
109114 $ this ->logger ->warning ('Failed to define an expiration for the "{resource}" lock, someone else acquired the lock. ' , array ('resource ' => $ this ->key ));
110115 throw $ e ;
111116 } catch (\Exception $ e ) {
@@ -119,7 +124,7 @@ public function refresh()
119124 */
120125 public function isAcquired ()
121126 {
122- return $ this ->store ->exists ($ this ->key );
127+ return $ this ->dirty = $ this -> store ->exists ($ this ->key );
123128 }
124129
125130 /**
@@ -128,6 +133,7 @@ public function isAcquired()
128133 public function release ()
129134 {
130135 $ this ->store ->delete ($ this ->key );
136+ $ this ->dirty = false ;
131137
132138 if ($ this ->store ->exists ($ this ->key )) {
133139 $ this ->logger ->warning ('Failed to release the "{resource}" lock. ' , array ('resource ' => $ this ->key ));
0 commit comments