Class Worker

java.lang.Object
org.cojen.tupl.util.Worker

public class Worker extends Object
Simple task worker which has at most one background thread, and is expected to have only one thread enqueuing tasks. This class isn't thread safe for enqueuing tasks, and so the caller must provide its own mutual exclusion to protect against concurrent enqueues.
See Also:
  • Method Details

    • make

      public static Worker make(int maxSize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory)
      Parameters:
      maxSize - maximum amount of tasks which can be enqueued
      keepAliveTime - maximum idle time before worker thread exits
      unit - keepAliveTime time unit
      threadFactory - null for default
    • tryEnqueue

      public boolean tryEnqueue(Worker.Task task)
      Attempt to enqueue a task without blocking. When the task object is enqueued, it must not be used again for any other tasks.
      Returns:
      false if queue is full and task wasn't enqueued
    • enqueue

      public void enqueue(Worker.Task task)
      Enqueue a task, blocking if necessary until space is available. When the task object is enqueued, it must not be used again for any other tasks.
    • join

      public void join(boolean interrupt)
      Waits until the worker queue is drained and possibly interrupt it. If the worker thread is interrupted and exits, a new thread is started when new tasks are enqueued. The same mutual exclusion rules for enqueuing apply to this method too.
      Parameters:
      interrupt - pass true to interrupt the worker thread so that it exits
    • interrupt

      public void interrupt()
      Interrupt the worker thread, if it exists. If the worker thread is idle, this forces it to exit, but a new thread is started when new tasks are enqueued. This method can be safely called by any thread without any special mutual exclusion.