Java Class ThreadAPI

package jekdev.study.ports;

import jekpro.tools.api.*;

/**
 * <p>Java code for the API of the port sampler example.</p>
 * <p>This class provides an API to thread objects.</p>
 *
 * @author Copyright 2012, XLOG Technologies GmbH, Switzerland
 * @version Jekejeke Prolog 0.9.2 (a fast and small prolog interpreter)
 */
public final class ThreadAPI {
    private static final String OP_THREAD = "thread";
    private static final TermAtom ATOM_THREAD = new TermAtom(OP_THREAD);

    /**
     * <p>Start the sampler.</p>
     * <p>Java method called from Prolog.</p>
     *
     * @param inter The interpreter.
     * @return The output thread term.
     */
    public static Term startSampler(Interpreter inter) {
        ThreadHeadless thread = new ThreadHeadless(inter);
        thread.start();
        return wrapThread(inter, thread);
    }

    /**
     * <p>Stop the sampler.</p>
     * <p>Java method called from Prolog.</p>
     *
     * @param para The input thread term.
     * @throws InterpreterMessage Instantiation, 
     *                           domain or permission error.
     */
    public static void stopSampler(Term para) throws InterpreterMessage {
        ThreadHeadless thread = (ThreadHeadless) unwrapThread(para);
        thread.interrupt();
    }

    /**
     * <p>Wrap a mutex object into the mutex term.</p>
     * <p>Will create a term of the following form:</p>
     * <pre>
 * thread(ref) * </pre> * * @param inter The interpreter. * @param obj The mutex object. * @return The mutex term. */ private static TermCompound wrapThread(Interpreter inter, Thread obj) { return inter.createCompound(ATOM_THREAD, new Term[]{new TermRef(obj)}); } /** * <p>Unwrap a mutex object from the mutex term.</p> * <p>Will check whether the term has the following form:</p> * <pre>
* thread(ref) * </pre> * * @param para The stream term. * @return The stream object. * @throws InterpreterMessage * Instantiation or domain error. */ private static Thread unwrapThread(Term para)
throws
InterpreterMessage { if (para instanceof TermVar) throw new InterpreterMessage( InterpreterMessage.instantiationError()); if (!(para instanceof TermCompound) || ((TermCompound) para).getArity() != 1 || !((TermCompound) para).getFunctor().equals(ATOM_THREAD)) throw new InterpreterMessage( InterpreterMessage.domainError(OP_THREAD, para)); Term para2 = ((TermCompound) para).getArg(0); if (para2 instanceof TermVar) throw new InterpreterMessage( InterpreterMessage.instantiationError()); if (!(para2 instanceof TermRef) || !(((TermRef) para2).getValue() instanceof Thread)) throw new InterpreterMessage( InterpreterMessage.domainError(OP_THREAD, para)); return (Thread) ((TermRef) para2).getValue(); } }

Comments