Garbage collector
15811
protected function gcCycle() {
		$lockPath    = $this->deferredDir . DIRECTORY_SEPARATOR . '.zdebug_gclock';
		$currentTime = time();

		// Check the lock file and expiration time
		if (is_file($lockPath) && filemtime($lockPath) + $this->gcLockLifetime > $currentTime) {
			return;
		}

		if (! touch($lockPath)) {
			throw new GcError('Unable to create or update the lock file while a garbage collection cycle');
		}

		$profilesDir = new DirectoryIterator($this->deferredDir);
		
		foreach ($profilesDir as $file) {
			if (! $file->isFile()) {
				continue;
			}

			$fileName = $file->getFilename();

			if (strpos($fileName, 'profile_') !== 0) {
				continue;
			}

			if ($file->getMTime() + $this->profilesGcTime < $currentTime) {
				unlink($file->getRealPath());
			}
		}
	}
819567
@Override
    protected void classLoaderChanged()
    {
        Vector toRemove = new Vector(); // safely remove
        for ( Enumeration e = listeners.elements(); e.hasMoreElements(); )
        {
            WeakReference wr = (WeakReference)e.nextElement();
            Listener l = (Listener)wr.get();
            if ( l == null )  // garbage collected
              toRemove.add( wr );
            else
              l.classLoaderChanged();
        }
        for( Enumeration e = toRemove.elements(); e.hasMoreElements(); )
            listeners.removeElement( e.nextElement() );
    }
258612
def register(self, collector):
        
        if not isinstance(collector, Collector):
            raise TypeError(
                "Can't register instance, not a valid type of collector")

        if collector.name in self.collectors:
            raise ValueError("Collector already exists or name colision")

        with mutex:
            self.collectors[collector.name] = collector
273641
public function garbageCollect()
    {
        // Flush cache
        $this->cellCollection->getCacheData('A1');
        // Build a reference table from images
//        $imageCoordinates = array();
//        $iterator = $this->getDrawingCollection()->getIterator();
//        while ($iterator->valid()) {
//            $imageCoordinates[$iterator->current()->getCoordinates()] = true;
//
//            $iterator->next();
//        }
//
        // Lookup highest column and highest row if cells are cleaned
        $colRow = $this->cellCollection->getHighestRowAndColumn();
        $highestRow = $colRow['row'];
        $highestColumn = PHPExcel_Cell::columnIndexFromString($colRow['column']);

        // Loop through column dimensions
        foreach ($this->columnDimensions as $dimension) {
            $highestColumn = max($highestColumn, PHPExcel_Cell::columnIndexFromString($dimension->getColumnIndex()));
        }

        // Loop through row dimensions
        foreach ($this->rowDimensions as $dimension) {
            $highestRow = max($highestRow, $dimension->getRowIndex());
        }

        // Cache values
        if ($highestColumn < 0) {
            $this->cachedHighestColumn = 'A';
        } else {
            $this->cachedHighestColumn = PHPExcel_Cell::stringFromColumnIndex(--$highestColumn);
        }
        $this->cachedHighestRow = $highestRow;

        // Return
        return $this;
    }
68380
public function on_garbage_collection()
	{
		if (substr($GLOBALS['request']->server('SCRIPT_NAME'), -7) === 'app.php')
		{
			return;
		}

		// An Exception is throw because the TraceableEventDispatcher
		// stop all the events when KernelEvents::RESPONSE is trigger.
		// But because we are emulating the event through the
		// garbage_collection event, we got an exception at the end
		// of the dispatching of the event.
		// (stop() is called on an already stopped() event)
		set_exception_handler(array($this, 'exception_handler'));

		try {
			$response = new Response('<html><body></body></html>');
			$this->dispatcher->dispatch(KernelEvents::RESPONSE,
				new FilterResponseEvent(
					$this->http_kernel,
					$this->request_stack->getCurrentRequest(),
					HttpKernelInterface::MASTER_REQUEST,
					$response
				));

			if ($this->redirect_url !== null)
			{
				$url = $this->redirect_url;

				// Redirect via an HTML form for PITA webservers
				if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
				{
					header('Refresh: 0; URL=' . $url);

					echo '<!DOCTYPE html>';
					echo '<html dir="Direction" lang="en">';
					echo '<head>';
					echo '<meta charset="utf-8">';
					echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&amp;', $url) . '" />';
					echo '<title>Redirect</title>';
					echo '</head>';
					echo '<body>';
					echo '<div style="text-align: center;"><a href="' . str_replace('&', '&amp;', $url) . '">Redirect</a></div>';
					echo '</body>';
					echo '</html>';

					$this->dispatcher->dispatch(KernelEvents::TERMINATE,
					new PostResponseEvent($this->http_kernel,
							$this->request_stack->getCurrentRequest(),
							$response
						)
					);
					exit;
				}

				// Behave as per HTTP/1.1 spec for others
				header('Location: ' . $url);
				$this->dispatcher->dispatch(KernelEvents::TERMINATE,
					new PostResponseEvent($this->http_kernel,
						$this->request_stack->getCurrentRequest(),
						$response
					)
				);
				exit;
			}
			else if ($response->getContent() !== '<html><body></body></html>')
			{
				if ('<html><body></body></html>' !== $response->getContent())
				{
					echo $response->getContent();
				}
			}

			$this->dispatcher->dispatch(KernelEvents::TERMINATE,
				new PostResponseEvent($this->http_kernel,
					$this->request_stack->getCurrentRequest(),
					$response
				)
			);
		}
		catch (\Exception $e)
		{dump($e);
		}
	}
351143
static function gc()
    {
        $rcube = rcube::get_instance();
        $db    = $rcube->get_dbh();
        $now   = $db->now();

        $db->query("DELETE FROM " . $db->table_name('cache_messages', true)
              ." WHERE `expires` < $now");

        $db->query("DELETE FROM " . $db->table_name('cache_index', true)
              ." WHERE `expires` < $now");

        $db->query("DELETE FROM ".$db->table_name('cache_thread', true)
              ." WHERE `expires` < $now");
    }
884561
private void gc() {

        I_CmsLruCacheObject currentObject = m_listTail;
        while (currentObject != null) {
            if (m_objectCosts < m_avgCacheCosts) {
                break;
            }
            currentObject = currentObject.getNextLruObject();
            removeTail();
        }
    }
41480
public void setMemoryHandler(@NonNull MemoryHandler memoryHandler) {
        globalLock.writeLock().lock();

        this.memoryHandler = memoryHandler;
        this.memoryHandler.init(configuration, this);

        globalLock.writeLock().unlock();
    }
544433
public function garbageCollector() {
		$conditions = [
			$this->getAlias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity),
		];
		return $this->deleteAll($conditions);
	}
32171
private void gc() {
    if ((services != null && services.isConnected()) && debugger != null) {
      debugger.releaseObjects();
    }
    objectIds.clear();
  }
755590
def _try_to_clean_garbage(self, writer_spec, exclude_list=()):
    
    # Try to remove garbage (if any). Note that listbucket is not strongly
    # consistent so something might survive.
    tmpl = string.Template(self._TMPFILE_PREFIX)
    prefix = tmpl.substitute(
        id=self.status.mapreduce_id, shard=self.status.shard)
    bucket = self._get_tmp_gcs_bucket(writer_spec)
    account_id = self._get_tmp_account_id(writer_spec)
    for f in cloudstorage.listbucket("/%s/%s" % (bucket, prefix),
                                     _account_id=account_id):
      if f.filename not in exclude_list:
        self._remove_tmpfile(f.filename, self.status.writer_spec)
192958
protected function garbageCollect()
    {
        foreach (Finder::create()->files()->name('*.json')->date('< ' . $this->gc_lifetime . ' hour ago')->in(
            $this->dirname
        ) as $file) {
            $this->files->delete($file->getRealPath());
        }
    }
243462
public long cleanup() {
		int garbageSize = 0;
		if (isCachingEnabled()) {
			System.out.println(new LogEntry(Level.VERBOSE, "Identifying expired objects"));
			ArrayList<K> garbage = getExpiredObjects();
			garbageSize = garbage.size();
			System.out.println(new LogEntry("cache cleanup: expired objects: " + garbageSize));
			for (K key : garbage) {
				clear(key);
			}
		}
		return garbageSize;
	}
472348
public static void main(String argv[]) throws Exception {
    StringUtils.startupShutdownMessage(UtilizationCollector.class, argv, LOG);
    try {
      Configuration conf = new Configuration();
      UtilizationCollector collector = new UtilizationCollector(conf);
      if (collector != null) {
        collector.join();
      }
    } catch (Throwable e) {
      LOG.error(StringUtils.stringifyException(e));
      System.exit(-1);
    }
  }
859070
function acquireMemoryObserver() {
  // Only enable on first use.
  ++memoryObservationCount;
  if (memoryObservationCount > 1) {
    return;
  }

  // Enable memory notification.
  setTemporaryPreference('javascript.options.mem.notify', true);

  // Listen for events.
  Services.obs.addObserver(
      handleMemoryEvent, 'garbage-collection-statistics', false);
}
166572
def write_memory_dump():
    
    # first do a full garbage collection run
    gc.collect()
    if gc.garbage:
        log.warn(LOG_CHECK, "Unreachabe objects: %s", pprint.pformat(gc.garbage))
    from meliae import scanner
    fo, filename = get_temp_file(mode='wb', suffix='.json', prefix='lcdump_')
    try:
        scanner.dump_all_objects(fo)
    finally:
        fo.close()
    return filename
806214
public function setGarbage($garbage, \DateTime $garbageTimestamp = null)
    {
        $this->garbage = $garbage;

        if ($garbageTimestamp == null)
        {
            $garbageTimestamp = new \DateTime();
        }
        $this->setGarbageTimestamp($garbageTimestamp);

        return $this;
    }