Class Fiber<V>

  • Type Parameters:
    V - The type of the fiber's result value. Should be set to Void if no value is to be returned by the fiber.
    All Implemented Interfaces:
    Joinable<V>, java.io.Serializable, java.util.concurrent.Future<V>

    public class Fiber<V>
    extends Strand
    implements Joinable<V>, java.io.Serializable, java.util.concurrent.Future<V>
    A lightweight thread.

    There are two ways to create a new fiber: either subclass the Fiber class and override the run method, or pass the code to be executed in the fiber as the target parameter to the constructor. All in all, the Fiber API resembles the Thread class in many ways.

    A fiber runs inside a ForkJoinPool.

    A Fiber can be serialized if it's not running and all involved classes and data types are also Serializable.

    A new Fiber occupies under 400 bytes of memory (when using the default stack size, and compressed OOPs are turned on, as they are by default).

    See Also:
    Serialized Form
    • Field Detail

      • flightRecorder

        protected static final co.paralleluniverse.common.monitoring.FlightRecorder flightRecorder
    • Constructor Detail

      • Fiber

        public Fiber​(java.lang.String name,
                     FiberScheduler scheduler,
                     SuspendableCallable<V> target)
        Creates a new Fiber from the given SuspendableCallable. The new fiber uses the default initial stack size.
        Parameters:
        name - The name of the fiber (may be null)
        scheduler - The scheduler pool in which the fiber should run.
        target - the SuspendableCallable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(FiberScheduler scheduler,
                     SuspendableCallable<V> target)
        Creates a new Fiber from the given SuspendableCallable. The new fiber has no name, and uses the default initial stack size.
        Parameters:
        scheduler - The scheduler pool in which the fiber should run.
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     FiberScheduler scheduler,
                     int stackSize,
                     SuspendableRunnable target)
        Creates a new Fiber from the given SuspendableRunnable.
        Parameters:
        name - The name of the fiber (may be null)
        scheduler - The scheduler pool in which the fiber should run.
        stackSize - the initial size of the data stack.
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     FiberScheduler scheduler,
                     SuspendableRunnable target)
        Creates a new Fiber from the given SuspendableRunnable. The new fiber uses the default initial stack size.
        Parameters:
        name - The name of the fiber (may be null)
        scheduler - The scheduler pool in which the fiber should run.
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(FiberScheduler scheduler,
                     SuspendableRunnable target)
        Creates a new Fiber from the given SuspendableRunnable. The new fiber has no name, and uses the default initial stack size.
        Parameters:
        scheduler - The scheduler pool in which the fiber should run.
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     FiberScheduler scheduler,
                     int stackSize)
        Creates a new Fiber subclassing the Fiber class and overriding the run method.
        Parameters:
        name - The name of the fiber (may be null)
        scheduler - The scheduler pool in which the fiber should run.
        stackSize - the initial size of the data stack.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     FiberScheduler scheduler)
        Creates a new Fiber subclassing the Fiber class and overriding the run method. The new fiber uses the default initial stack size.
        Parameters:
        name - The name of the fiber (may be null)
        scheduler - The scheduler pool in which the fiber should run.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(FiberScheduler scheduler)
        Creates a new Fiber subclassing the Fiber class and overriding the run method. The new fiber has no name, and uses the default initial stack size.
        Parameters:
        scheduler - The scheduler pool in which the fiber should run.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     SuspendableCallable<V> target)
        Creates a new child Fiber from the given SuspendableCallable. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber. The new fiber uses the default initial stack size.
        Parameters:
        name - The name of the fiber (may be null)
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(SuspendableCallable<V> target)
        Creates a new child Fiber from the given SuspendableCallable. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber. The new fiber has no name, and uses the default initial stack size.
        Parameters:
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     int stackSize,
                     SuspendableRunnable target)
        Creates a new child Fiber from the given SuspendableRunnable. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber.
        Parameters:
        name - The name of the fiber (may be null)
        stackSize - the initial size of the data stack.
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     SuspendableRunnable target)
        Creates a new child Fiber from the given SuspendableRunnable. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber. The new fiber uses the default initial stack size.
        Parameters:
        name - The name of the fiber (may be null)
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(SuspendableRunnable target)
        Creates a new child Fiber from the given SuspendableRunnable. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber. The new fiber has no name, and uses the default initial stack size.
        Parameters:
        target - the SuspendableRunnable for the Fiber.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name,
                     int stackSize)
        Creates a new child Fiber subclassing the Fiber class and overriding the run method. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber.
        Parameters:
        name - The name of the fiber (may be null)
        stackSize - the initial size of the data stack.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber​(java.lang.String name)
        Creates a new child Fiber subclassing the Fiber class and overriding the run method. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber. The new fiber uses the default initial stack size.
        Parameters:
        name - The name of the fiber (may be null)
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
      • Fiber

        public Fiber()
        Creates a new child Fiber subclassing the Fiber class and overriding the run method. This constructor may only be called from within another fiber. This fiber will use the same fork/join pool as the creating fiber. The new fiber has no name, and uses the default initial stack size.
        Throws:
        java.lang.NullPointerException - when proto is null
        java.lang.IllegalArgumentException - when stackSize is <= 0
    • Method Detail

      • hashCode

        public final int hashCode()
        Overrides:
        hashCode in class java.lang.Object
      • equals

        public final boolean equals​(java.lang.Object obj)
        Overrides:
        equals in class java.lang.Object
      • getName

        public final java.lang.String getName()
        Description copied from class: Strand
        Returns the strand's name.
        Specified by:
        getName in class Strand
        Returns:
        The strand's name. May be null.
      • setName

        public final Fiber<V> setName​(java.lang.String name)
        Description copied from class: Strand
        Sets this strand's name. This method may only be called before the strand is started.
        Specified by:
        setName in class Strand
        Parameters:
        name - the new name
        Returns:
        this
      • setPriority

        public Fiber setPriority​(int newPriority)
        Sets the priority of this fiber. The fiber priority's semantics - or even if it is ignored completely - is entirely up to the fiber's scheduler. The default fiber scheduler completely ignores fiber priority.
        Specified by:
        setPriority in class Strand
        Parameters:
        newPriority - priority to set this fiber to
        Throws:
        java.lang.IllegalArgumentException - If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY
        See Also:
        getPriority(), Strand.MAX_PRIORITY, Strand.MIN_PRIORITY
      • getPriority

        public int getPriority()
        Returns this fiber's priority.
        Specified by:
        getPriority in class Strand
        Returns:
        this strand's priority.
        See Also:
        setPriority(int)
      • getId

        public long getId()
        Description copied from class: Strand
        Returns the strand's id. Id's are unique within a single JVM instance.
        Specified by:
        getId in class Strand
      • getTask

        public java.lang.Object getTask()
      • setNoLocals

        @Deprecated
        public Fiber setNoLocals​(boolean value)
        Deprecated.
      • getNoLocals

        @Deprecated
        public boolean getNoLocals()
        Deprecated.
      • currentFiber

        public static Fiber currentFiber()
        Returns the active Fiber on this thread or NULL if no Fiber is running.
        Returns:
        the active Fiber on this thread or NULL if no Fiber is running.
      • isCurrentFiber

        public static boolean isCurrentFiber()
        Tests whether current code is executing in a fiber. This method might be faster than Fiber.currentFiber() != null.
        Returns:
        true if called in a fiber; false otherwise.
      • getCurrentRun

        public static long getCurrentRun()
      • isFiber

        public final boolean isFiber()
        Description copied from class: Strand
        Tests whether this strand is a fiber.
        Specified by:
        isFiber in class Strand
        Returns:
        true iff this strand is a fiber.
      • getUnderlying

        public final java.lang.Object getUnderlying()
        Description copied from class: Strand
        Returns the underlying object of this strand, namely a Thread or a Fiber.
        Specified by:
        getUnderlying in class Strand
      • park

        public static boolean park​(java.lang.Object blocker,
                                   long timeout,
                                   java.util.concurrent.TimeUnit unit)
                            throws SuspendExecution
        Throws:
        SuspendExecution
      • sleep

        public static void sleep​(long millis)
                          throws java.lang.InterruptedException,
                                 SuspendExecution
        Throws:
        java.lang.InterruptedException
        SuspendExecution
      • sleep

        public static void sleep​(long millis,
                                 int nanos)
                          throws java.lang.InterruptedException,
                                 SuspendExecution
        Throws:
        java.lang.InterruptedException
        SuspendExecution
      • sleep

        public static void sleep​(long duration,
                                 java.util.concurrent.TimeUnit unit)
                          throws java.lang.InterruptedException,
                                 SuspendExecution
        Throws:
        java.lang.InterruptedException
        SuspendExecution
      • interrupted

        public static boolean interrupted()
      • getMonitor

        public co.paralleluniverse.fibers.FibersMonitor getMonitor()
      • inheritThreadLocals

        public Fiber inheritThreadLocals()
        Causes the current strand's thread-locals to be inherited by this fiber. By default only InheritableThreadLocals are inherited.

        This method must be called before the fiber is started (i.e. before the start method is called. Otherwise, an IllegalStateException is thrown.

        Returns:
        this
      • start

        public final Fiber<V> start()
        Description copied from class: Strand
        Starts the strand.
        Specified by:
        start in class Strand
        Returns:
        this
      • onParked

        protected void onParked()
      • shouldPreempt

        protected boolean shouldPreempt​(int type)
      • onCompletion

        protected void onCompletion()
      • onException

        protected void onException​(java.lang.Throwable t)
      • interrupt

        public final void interrupt()
        Description copied from class: Strand
        Interrupts this strand. If this strand is blocked, the blocking function will throw an InterruptedException. Otherwise, the strand may test its interrupted status with the Strand.interrupted() or Strand.isInterrupted() method.
        Specified by:
        interrupt in class Strand
      • getInterruptStack

        public final java.lang.InterruptedException getInterruptStack()
        Description copied from class: Strand
        Returns an InterruptedException that was created when the Strand.interrupt() method was called, and can be used to retrieve the stack trace of the strand that interrupted this strand. This method is only intended to assist in debugging. This method may return null if this information is not available. The current implementation always returns null if this strand is a thread.
        Specified by:
        getInterruptStack in class Strand
      • isAlive

        public final boolean isAlive()
        Description copied from class: Strand
        Tests whether this strand is alive, namely it has been started but not yet terminated.
        Specified by:
        isAlive in class Strand
      • getState

        public final Strand.State getState()
        Description copied from class: Strand
        Returns the strand's current running state.
        Specified by:
        getState in class Strand
      • isTerminated

        public final boolean isTerminated()
        Description copied from class: Strand
        Tests whether this strand has terminated.
        Specified by:
        isTerminated in class Strand
      • getBlocker

        public final java.lang.Object getBlocker()
        Description copied from class: Strand
        Returns the blocker object supplied to the most recent invocation of a park method that has not yet unblocked, or null if not blocked. The value returned is just a momentary snapshot -- the thread may have since unblocked or blocked on a different blocker object.
        Specified by:
        getBlocker in class Strand
        Returns:
        the blocker
      • unpark

        public final void unpark()
        Makes available the permit for this fiber, if it was not already available. If the fiber was blocked on park then it will unblock. Otherwise, its next call to park is guaranteed not to block.
        Specified by:
        unpark in class Strand
      • unpark

        public final void unpark​(java.lang.Object unblocker)
        Description copied from class: Strand
        Makes available the permit for this strand, if it was not already available. If this strand was blocked on Strand.park() then it will unblock. Otherwise, its next call to Strand.park() is guaranteed not to block. This operation is not guaranteed to have any effect at all if the given strand has not been started.
        Specified by:
        unpark in class Strand
        Parameters:
        unblocker - the synchronization object responsible for this strand unparking
      • join

        @Suspendable
        public final void join()
                        throws java.util.concurrent.ExecutionException,
                               java.lang.InterruptedException
        Description copied from class: Strand
        Awaits the termination of this strand. This method blocks until this strand terminates.
        Specified by:
        join in interface Joinable<V>
        Specified by:
        join in class Strand
        Throws:
        java.util.concurrent.ExecutionException - if this strand has terminated as a result of an uncaught exception (which will be the cause of the thrown ExecutionException.
        java.lang.InterruptedException
      • join

        @Suspendable
        public final void join​(long timeout,
                               java.util.concurrent.TimeUnit unit)
                        throws java.util.concurrent.ExecutionException,
                               java.lang.InterruptedException,
                               java.util.concurrent.TimeoutException
        Description copied from class: Strand
        Awaits the termination of this strand, at most for the timeout duration specified. This method blocks until this strand terminates or the timeout elapses.
        Specified by:
        join in interface Joinable<V>
        Specified by:
        join in class Strand
        Parameters:
        timeout - the maximum duration to wait for the strand to terminate in the time unit specified by unit.
        unit - the time unit of timeout.
        Throws:
        java.util.concurrent.ExecutionException - if this strand has terminated as a result of an uncaught exception (which will be the cause of the thrown ExecutionException.
        java.util.concurrent.TimeoutException - if this strand did not terminate by the time the timeout has elapsed.
        java.lang.InterruptedException
      • joinNoSuspend

        public final Fiber<V> joinNoSuspend()
                                     throws java.util.concurrent.ExecutionException,
                                            java.lang.InterruptedException
        Throws:
        java.util.concurrent.ExecutionException
        java.lang.InterruptedException
      • joinNoSuspend

        public final Fiber<V> joinNoSuspend​(long timeout,
                                            java.util.concurrent.TimeUnit unit)
                                     throws java.util.concurrent.ExecutionException,
                                            java.lang.InterruptedException,
                                            java.util.concurrent.TimeoutException
        Throws:
        java.util.concurrent.ExecutionException
        java.lang.InterruptedException
        java.util.concurrent.TimeoutException
      • get

        @Suspendable
        public final V get()
                    throws java.util.concurrent.ExecutionException,
                           java.lang.InterruptedException
        Specified by:
        get in interface java.util.concurrent.Future<V>
        Specified by:
        get in interface Joinable<V>
        Specified by:
        get in class Strand
        Throws:
        java.util.concurrent.ExecutionException
        java.lang.InterruptedException
      • get

        @Suspendable
        public final V get​(long timeout,
                           java.util.concurrent.TimeUnit unit)
                    throws java.util.concurrent.ExecutionException,
                           java.lang.InterruptedException,
                           java.util.concurrent.TimeoutException
        Specified by:
        get in interface java.util.concurrent.Future<V>
        Specified by:
        get in interface Joinable<V>
        Specified by:
        get in class Strand
        Throws:
        java.util.concurrent.ExecutionException
        java.lang.InterruptedException
        java.util.concurrent.TimeoutException
      • isDone

        public final boolean isDone()
        Specified by:
        isDone in interface java.util.concurrent.Future<V>
        Specified by:
        isDone in interface Joinable<V>
        Overrides:
        isDone in class Strand
      • cancel

        public final boolean cancel​(boolean mayInterruptIfRunning)
        Specified by:
        cancel in interface java.util.concurrent.Future<V>
      • isCancelled

        public final boolean isCancelled()
        Specified by:
        isCancelled in interface java.util.concurrent.Future<V>
      • getStackTrace

        public final java.lang.StackTraceElement[] getStackTrace()
        Description copied from class: Strand
        Returns an array of stack trace elements representing the stack dump of this strand. This method will return a zero-length array if this strand has not started, has started but has not yet been scheduled to run by the system, or has terminated. If the returned array is of non-zero length then the first element of the array represents the top of the stack, which is the most recent method invocation in the sequence. The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

        Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this strand is permitted to return a zero-length array from this method.

        Specified by:
        getStackTrace in class Strand
        Returns:
        an array of StackTraceElements, each represents one stack frame.
      • dumpStack

        public static void dumpStack()
      • toString

        public final java.lang.String toString()
        Overrides:
        toString in class java.lang.Object
      • isRecordingLevel

        protected final boolean isRecordingLevel​(int level)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object arg1)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object arg1,
                                    java.lang.Object arg2)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object arg1,
                                    java.lang.Object arg2,
                                    java.lang.Object arg3)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object arg1,
                                    java.lang.Object arg2,
                                    java.lang.Object arg3,
                                    java.lang.Object arg4)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object arg1,
                                    java.lang.Object arg2,
                                    java.lang.Object arg3,
                                    java.lang.Object arg4,
                                    java.lang.Object arg5)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object arg1,
                                    java.lang.Object arg2,
                                    java.lang.Object arg3,
                                    java.lang.Object arg4,
                                    java.lang.Object arg5,
                                    java.lang.Object arg6)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object arg1,
                                    java.lang.Object arg2,
                                    java.lang.Object arg3,
                                    java.lang.Object arg4,
                                    java.lang.Object arg5,
                                    java.lang.Object arg6,
                                    java.lang.Object arg7)
      • record

        protected final void record​(int level,
                                    java.lang.String clazz,
                                    java.lang.String method,
                                    java.lang.String format,
                                    java.lang.Object... args)
      • parkAndSerialize

        public static void parkAndSerialize​(FiberWriter writer)
                                     throws SuspendExecution
        Parks the fiber and allows the given callback to serialize it.
        Parameters:
        writer - a callback that can serialize the fiber.
        Throws:
        SuspendExecution
      • parkAndCustomSerialize

        public static void parkAndCustomSerialize​(CustomFiberWriter writer)
                                           throws SuspendExecution
        Parks the fiber and allows the given callback to serialize it, optimized for use cases where the callback object has a custom way to obtain the required serializer (e.g. from a serializer pool)
        Parameters:
        writer - a callback that can serialize the fiber.
        Throws:
        SuspendExecution
      • unparkSerialized

        public static <V> Fiber<V> unparkSerialized​(byte[] serFiber,
                                                    FiberScheduler scheduler)
        Deserializes a fiber from the given byte array and unparks it.
        Parameters:
        serFiber - The byte array containing a fiber's serialized form.
        scheduler - The FiberScheduler to use for scheduling the fiber.
        Returns:
        The deserialized, running fiber.
      • unparkDeserialized

        public static <V> Fiber<V> unparkDeserialized​(Fiber<V> f,
                                                      FiberScheduler scheduler)
        Unparks a fiber that's been deserialized (with the help of getFiberSerializer()
        Parameters:
        f - The deserialized fiber
        scheduler - The FiberScheduler to use for scheduling the fiber.
        Returns:
        The fiber
      • getFiberSerializer

        public static co.paralleluniverse.io.serialization.ByteArraySerializer getFiberSerializer()
        Returns a ByteArraySerializer capable of serializing an object graph containing fibers.
      • getFiberSerializer

        public static co.paralleluniverse.io.serialization.ByteArraySerializer getFiberSerializer​(boolean includeThreadLocals)
        Returns a ByteArraySerializer capable of serializing an object graph containing fibers.
        Parameters:
        includeThreadLocals - if true, thread/fiber local storage slots will also be serialised. You may want to set this to false if you are using frameworks that put things that cannot be properly serialised into TLS slots, or if the feature causes other issues.