package de.renew.util;

class PoolThread extends Thread {
    private final Semaphor _startSem = new Semaphor();
    private Runnable _runnable;

    /**
     * Creates a new <code>PoolThread</code> instance.
     * Such thread start immediately, but will wait until
     * a runnable is passed to them.
     */
    PoolThread() {
        start();
    }

    /**
     * Either execute a runnable or discard the pool thread.
     *
     * @param runnable <code>null</code> to discard this object,
     *   any other value to execute a runnable
     */
    void executeOrDiscard(Runnable runnable) {
        this._runnable = runnable;
        _startSem.V();
    }

    @Override
    public void run() {
        while (true) {
            _startSem.P();
            if (_runnable == null) {
                return;
            }
            _runnable.run();


            // Allow garbage collection.
            _runnable = null;


            //Allow reuse of this pool thread.
            ThreadPool.put(this);
        }
    }
}