<?php


namespace Mainto\RpcServer\RpcUtil;


class RpcGCHelper {
    private $lastGcTime = null;
    private $maxLifeTime = 60;
    private $gcProbability = 5;

    /**
     * RpcGCHelper constructor.
     */
    public function __construct () {
        gc_enable();

        $this->lastGcTime = time();
        $this->maxLifeTime = config("rpc-server.gc.max_lifetime", 60);
        $this->gcProbability = config("rpc-server.gc.probability", 5);
    }

    public static function getInstance () {
        static $instance = null;

        if ($instance == null) {
            $instance = new RpcGCHelper();
        }

        return $instance;
    }

    /**
     * test need run gc
     *
     * @return bool
     */
    private function canRunGC () {
        $now = time();

        if (rand(0, 100) <= $this->gcProbability) {
            $this->lastGcTime = $now;

            return true;
        }

        if ($now - $this->lastGcTime > $this->maxLifeTime) {
            $this->lastGcTime = $now;

            return true;
        }

        return false;
    }

    /**
     * 触发单次GC
     * @param bool $force
     */
    public function hitGC ($force = false) {
        if ($force || $this->canRunGC()) {
            gc_collect_cycles();
            gc_mem_caches();
        }
    }
}