I use the file system to create a application wide persistent singleton (application does not use a database). Occasionally a page will take 1-2 minutes to load and I have narrowed the problem down to the use of flock in the function that gets an instance of the singleton. Here is a simplified version of the code: (edit: left out the most important part of the code in my original post)
public static final function getInstance() {
if (is_null(self::$instance) {
$fh = fopen($filename, 'ab+');
if (flock($fh, LOCK_EX)) {
$N = filesize($filename);
if ($N > 0) {
rewind($fh);
$s = stream_get_contents($fh);
$obj = unserialize($s);
} else {
$obj = new MyClass();
}
self::$instance = $obj;
return $obj;
} else {
fclose($fh);
trigger_error("could not create lock", E_USER_WARNING);
}
} else {
return self::$instance;
}
}
The code is currently being run my development machine which uses XP and NTFS.
The lock is always created (i.e. trigger_error is not called).
The delay is random but seems to happen more often when refresh is hit.
Getting rid of flock completely eliminates the problem but it also makes the code unsafe.
Any advice?
Does anyone know a better way of creating an application wide persistent singleton?