Java Class ThreadHeadless

package jekdev.study.ports;

import jekdev.platform.headless.CapabilityDevelopment;
import jekpro.tools.api.Interpreter;
import jekpro.tools.api.InterpreterMessage;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>The port sampler thread.</p>
 *
 * @author Copyright 2012, XLOG Technologies GmbH, Switzerland
 * @version Jekejeke Prolog 0.9.3 (a fast and small prolog interpreter)
 */
final class ThreadHeadless extends Thread {
    private static final long NANOS_PER_MILLI = 1000000;
    private static final long[] SLEEP = {NANOS_PER_MILLI / 2, 
                                         2* NANOS_PER_MILLI};

    private Interpreter inter;
    private boolean on;
    private ReentrantLock lock = new ReentrantLock();
    private Condition cond = lock.newCondition();

    /**
     * <p>Create a port sampler thread.</p>
     *
     * @param i The interpreter.
     */
    ThreadHeadless(Interpreter i) {
        inter = i;
    }

    /**
     * <p>Constantly update the chart.</p>
     */
    public void run() {
        try {
            lock.lock();
            for (; ; ) {
                long lastTime = System.nanoTime();
                try {
                    inter.setStatus(
                      CapabilityDevelopment.STATUS_SYS_TRACE_MODE, on);
                } catch (InterpreterMessage x) {
                    throw new RuntimeException(x);
                }
                long sleep = SLEEP[on ? 1 : 0] – 
                      (System.nanoTime() - lastTime);
                try {
                    while (sleep > 0)
                        sleep = cond.awaitNanos(sleep);
                } catch (InterruptedException x) {
                    return;
                }
                on = !on;
            }
        } finally {
            lock.unlock();
        }
    }

}

Comments