Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 296717
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T06:34:27+00:00 2026-05-12T06:34:27+00:00

I just started playing with memcache(d) last night so I have a LOT to

  • 0

I just started playing with memcache(d) last night so I have a LOT to learn about it

I am wanting to know if this code is a good way of doing what it is doing or if I should be using other memcache functions

I want to show a cache version of something, if the cache does not exist then I generate the content from mysql and set it into cache then show the mysql result on the page, then next page load it will check cache and see that it is there, so it will show it.

This code seems to do the trick but there are several different memcache functions should I be using other ones to accomplish this?

<?PHP
$memcache= new Memcache();
$memcache->connect('127.0.0.1', 11211);

$rows2= $memcache->get('therows1');
if($rows2 == ''){
    $myfriends = findfriend2(); // this function gets our array from mysql
    $memcache->set('therows1', $myfriends, 0, 30);
    echo '<pre>';
    print_r($myfriends); // print the mysql version
    echo '</pre>';
}else{
    echo '<pre>';
    print_r($rows2); //print the cached version
    echo '</pre>';
}
?>

Here is the locking function provided in the link posted by @crescentfresh

<?PHP
// {{{ locked_mecache_update($memcache,$key,$updateFunction,$expiryTime,$waitUTime,$maxTries)
/**
 * A function to do ensure only one thing can update a memcache at a time.
 *
 * Note that there are issues with the $expiryTime on memcache not being
 * fine enough, but this is the best I can do. The idea behind this form
 * of locking is that it takes advantage of the fact that
 * {@link memcache_add()}'s are atomic in nature.
 *
 * It would be possible to be a more interesting limiter (say that limits
 * updates to no more than 1/second) simply by storing a timestamp or
 * something of that nature with the lock key (currently stores "1") and
 * not deleitng the memcache entry.
 *
 * @package TGIFramework
 * @subpackage functions
 * @copyright 2009 terry chay
 * @author terry chay &lt;tychay@php.net&gt;
 * @param $memcache memcache the memcache object
 * @param $key string the key to do the update on
 * @param $updateFunction mixed the function to call that accepts the data
 *  from memcache and modifies it (use pass by reference).
 * @param $expiryTime integer time in seconds to allow the key to last before
 *  it will expire. This should only happen if the process dies during update.
 *  Choose a number big enough so that $updateFunction will take much less
 *  time to execute.
 * @param $waitUTime integer the amount of time in microseconds to wait before
 *  checking for the lock to release
 * @param $maxTries integer maximum number of attempts before it gives up
 *  on the locks. Note that if $maxTries is 0, then it will RickRoll forever
 *  (never give up). The default number ensures that it will wait for three
 *  full lock cycles to crash before it gives up also.
 * @return boolean success or failure
 */
function locked_memcache_update($memcache, $key, $updateFunction, $expiryTime=3, $waitUtime=101, $maxTries=100000)
{
    $lock = 'lock:'.$key;

    // get the lock {{{
    if ($maxTries>0) {
        for ($tries=0; $tries< $maxTries; ++$tries) {
            if ($memcache->add($lock,1,0,$expiryTime)) { break; }
            usleep($waitUtime);
        }
        if ($tries == $maxTries) {
            // handle failure case (use exceptions and try-catch if you need to be nice)
            trigger_error(sprintf('Lock failed for key: %s',$key), E_USER_NOTICE);
            return false;
        }
    } else {
        while (!$memcache->add($lock,1,0,$expiryTime)) {
            usleep($waitUtime);
        }
    }
    // }}}
    // modify data in cache {{{
    $data = $memcache->get($key, $flag);
    call_user_func($updateFunction, $data); // update data
    $memcache->set($key, $data, $flag);
    // }}}
    // clear the lock
    $memcache->delete($lock,0);
    return true;
}
// }}}
?>
  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T06:34:28+00:00Added an answer on May 12, 2026 at 6:34 am

    Couple things.

    1. you should be checking for false, not '' using === in the return value from get(). php’s type conversions save you from doing that here, but IMHO it’s better to be explicit about the value you are looking for from a cache lookup
    2. You’ve got a race condition there between the empty check and where you set() the db results. From http://code.google.com/p/memcached/wiki/FAQ#Race_conditions_and_stale_data:

      Remember that the process of checking
      memcached, fetching SQL, and storing
      into memcached, is not atomic at all!

      The symptoms of this are a spike in the DB CPU when the key expires and (on a high volume site) a bunch of requests simultaneously trying to hit the db and cache the value.

      You can solve it by using add() instead of get. See a more concrete example here.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I just started playing around with JSON and I have created this example. var
i have just started playing aorund with asp.net mvc and i want to view
I've just started playing with PowerMock and EasyMock and I'm a bit confused about
Good evening, I just started playing with Microsoft.Contracts (latest version) and plugging it on
I just started playing about with emacs yesterday for a project I'm working on.
I just started playing around with MSBuild this evening and am porting an nAnt
I've just started playing around with Scala, and I just learned about how methods
Possible Duplicate: Is JavaScript's Math broken? I have just started playing around with Javascript
I´ve just started playing around with Java and Hibernate and have gotten an application
I have just started playing with TeamCity and its great. Now I got it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.