zend-cache icon indicating copy to clipboard operation
zend-cache copied to clipboard

Idea: add getItemWithCallback method

Open remicollet opened this issue 10 years ago • 4 comments

Implementation could looks like

function getItemWithCallback($key, $callback) {
   $item = $this->getItem($key);
   if ($item === false) {
       $item = $callback($key);
       $this->setItem($key, $item);
   }
   return $item;
}

And with APCu 5.1, this can be override to use new "apcu_entry" API which will manage a lock to avoid bad run race condition, and a single execution of the callback.

remicollet avatar Nov 27 '15 18:11 remicollet

@remicollet thanks for this great idea!

A few questions:

When control enters apcu_entry() the lock for the cache is acquired exclusively, it is released when control leaves apcu_entry()

  • Does that mean the lock for the exact same entry/key or are there other entries/keys effected, too?
  • "exclusively" means other processes reading and writing the same key are waiting for the callback to finish.
    • Are other writes waiting for the lock to finish and afterwards overwrite the entry? Or are concurrent writes directly blocked (return false)? Does that makes sense?
    • -> This could happen if you have different logic writing the same entry like cache warm-up.

The only APCu function that can be called safely by generator is apcu_entry().

For me it means that the result of the callback will be automatically written to cache so your implementation would not be correct as it doesn't store the result. Or should the generator function take care or writing the valid result into cache? This would be more flexible because of some generator function doesn't throw exceptions or also could generate more than one entries.

Marc

marc-mabe avatar Nov 29 '15 12:11 marc-mabe

it doesn't store the result.

Fixed

remicollet avatar Nov 29 '15 16:11 remicollet

For APCU implementation, see https://github.com/krakjoe/apcu/blob/master/apc_cache.c#L1807

The idea is that the lock is set before the get, so this ensure the callback/store will be execute only once, and then used by other process.

I think this make sense expecially when the cached value require very long computation.

remicollet avatar Nov 29 '15 16:11 remicollet

This repository has been closed and moved to laminas/laminas-cache; a new issue has been opened at https://github.com/laminas/laminas-cache/issues/11.

weierophinney avatar Dec 31 '19 21:12 weierophinney