Worker

value class Worker(source)

Class representing a worker.

Worker represents a thread of execution and a queue of work sent to this worker. Once started, the worker processes its own queue until it is explicitly terminated.

Worker's API resembles both executor and threads API:

  • It is a resource that has to be closed.

    • Failure to terminatae and join the termination request leads to native memory leak.

    • It cannot be terminated externally while processing the work queue, leading to a crash.

  • It can be parked, but while parked, worker is allowed to process its own tasks' queue.

    • In order to unpark a worker, any task has to be submited to the worker.

  • The work can be sent to the worker both in forms of regular runnables and delayed (timed) runnables.

    • There is no mechanism to cancel delayed runnables.

  • Attempts to invoke any method of worker being terminated lead to a runtime exception.

    • It includes such things as innocuous Worker.current from the current worker.

Since Kotlin

1.3

Types

Link copied to clipboard
object Companion
Since Kotlin 1.3

Properties

Link copied to clipboard
val id: Int
Since Kotlin 1.3
Link copied to clipboard

Name of the worker, as specified in Worker.start or "worker $id" by default,

Since Kotlin 1.3
Link copied to clipboard

Get platform thread id of the worker thread.

Since Kotlin 1.3

Functions

Link copied to clipboard

Convert worker to a COpaquePointer value that could be passed via native void* pointer. Can be used as an argument of Worker.fromCPointer.

Since Kotlin 1.3
Link copied to clipboard
fun <T1, T2> execute(mode: TransferMode, producer: () -> T1, job: (T1) -> T2): Future<T2>

Plan job for further execution in the worker. Execute is a two-phase operation:

Since Kotlin 1.3
Link copied to clipboard
fun executeAfter(afterMicroseconds: Long = 0, operation: () -> Unit)

Plan job for further execution in the worker.

Since Kotlin 1.3
Link copied to clipboard
fun park(timeoutMicroseconds: Long, process: Boolean = false): Boolean

Park execution of the current worker until a new request arrives or timeout specified in timeoutMicroseconds elapsed. If process is true, pending queue elements are processed, including delayed requests. Note that multiple requests could be processed this way.

Since Kotlin 1.3
Link copied to clipboard

Process pending job(s) on the queue of this worker. Note that jobs scheduled with executeAfter using non-zero timeout are not processed this way. If termination request arrives while processing the queue via this API, worker is marked as terminated and will exit once the current request is done with.

Since Kotlin 1.3
Link copied to clipboard
fun requestTermination(processScheduledJobs: Boolean = true): Future<Unit>

Requests termination of the worker.

Since Kotlin 1.3
Link copied to clipboard
open override fun toString(): String

String representation of the worker.

Since Kotlin 1.3