All Downloads are FREE. Search and download functionalities are using the official Maven repository.

it.unibo.jakta.agents.fsm.impl.ThreadRunner.kt Maven / Gradle / Ivy

There is a newer version: 0.11.106
Show newest version
package it.unibo.jakta.agents.fsm.impl

import it.unibo.jakta.agents.fsm.Activity
import it.unibo.jakta.agents.fsm.time.Time
import it.unibo.jakta.agents.utils.Promise
import java.util.concurrent.Semaphore

/**
 * [AbstractRunner] implementation that executes the FSM on a separated thread.
 */
class ThreadRunner(override val activity: Activity) : AbstractRunner(activity) {
    private val promise = Promise()
    private val mutex = Semaphore(0)
    private val thread = Thread {
        while (!isOver) {
            safeExecute({ promise.completeExceptionally(it) }) {
                doStateTransition()
            }
        }
        promise.complete(null)
    }

    override fun onPause() = mutex.acquire()
    override fun onResume() = mutex.release()

    override fun getCurrentTime(): Time = Time.real(System.currentTimeMillis())

    override fun run(): Promise {
        thread.start()
        return promise.thenApplyAsync {
            thread.join()
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy