Package org.jruby

Class RubyThread

All Implemented Interfaces:
Serializable, Cloneable, Comparable<IRubyObject>, InstanceVariables, InternalVariables, IRubyObject, ExecutionContext, CoreObjectType

public class RubyThread extends RubyObject implements ExecutionContext
Implementation of Ruby's Thread class. Each Ruby thread is mapped to an underlying Java Virtual Machine thread.

Thread encapsulates the behavior of a thread of execution, including the main thread of the Ruby script. In the descriptions that follow, the parameter aSymbol refers to a symbol, which is either a quoted string or a Symbol (such as :name). Note: For CVS history, see ThreadClass.java.

See Also:
  • Field Details

    • RUBY_MIN_THREAD_PRIORITY

      public static final int RUBY_MIN_THREAD_PRIORITY
      See Also:
    • RUBY_MAX_THREAD_PRIORITY

      public static final int RUBY_MAX_THREAD_PRIORITY
      See Also:
  • Constructor Details

  • Method Details

    • getErrorInfo

      public IRubyObject getErrorInfo()
    • setErrorInfo

      public IRubyObject setErrorInfo(IRubyObject errorInfo)
    • setContext

      public void setContext(ThreadContext context)
    • clearContext

      public void clearContext()
    • getContext

      public ThreadContext getContext()
    • getNativeThread

      public Thread getNativeThread()
    • setFiberCurrentThread

      public void setFiberCurrentThread(RubyThread fiberCurrentThread)
    • getFiberCurrentThread

      public RubyThread getFiberCurrentThread()
    • beforeStart

      public void beforeStart()
      Perform pre-execution tasks once the native thread is running, but we have not yet called the Ruby code for the thread.
    • dispose

      public void dispose()
      Dispose of the current thread by tidying up connections to other stuff
    • createThreadClass

      public static RubyClass createThreadClass(ThreadContext context, RubyClass Object)
    • newInstance

      public static IRubyObject newInstance(IRubyObject recv, IRubyObject[] args, Block block)
      Thread.new

      Thread.new( [ arg ]* ) {| args | block }$ -> aThread

      Creates a new thread to execute the instructions given in block, and begins running it. Any arguments passed to Thread.new are passed into the block.

       x = Thread.new { sleep .1; print "x"; print "y"; print "z" }
       a = Thread.new { print "a"; print "b"; sleep .2; print "c" }
       x.join # Let the threads finish before
       a.join # main thread exits...
       
      produces: abxyzc
    • start

      @Deprecated(since="10.0") public static RubyThread start(IRubyObject recv, IRubyObject[] args, Block block)
      Deprecated.
    • start

      public static RubyThread start(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block)
      Basically the same as Thread.new . However, if class Thread is subclassed, then calling start in that subclass will not invoke the subclass's initialize method.
    • adopt

      public static RubyThread adopt(IRubyObject recv, Thread t)
    • adopt

      public static RubyThread adopt(Ruby runtime, ThreadService service, Thread thread)
    • initialize

      public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block)
    • startWaiterThread

      protected static RubyThread startWaiterThread(Ruby runtime, long pid, Block block)
    • cleanTerminate

      public void cleanTerminate(IRubyObject result)
    • beDead

      public void beDead()
    • pollThreadEvents

      public void pollThreadEvents()
    • pollThreadEvents

      public void pollThreadEvents(ThreadContext context, boolean blocking)
      Poll for thread events (raise, kill), propagating only events that are unmasked (see handle_interrupt(ThreadContext, IRubyObject, IRubyObject, Block) or intended to fire before blocking operations if blocking = true.
      Parameters:
      context - the context
      blocking - whether to trigger blocking operation interrupts
    • pollThreadEvents

      public void pollThreadEvents(ThreadContext context)
    • blockingThreadPoll

      public void blockingThreadPoll(ThreadContext context)
    • handle_interrupt

      public static IRubyObject handle_interrupt(ThreadContext context, IRubyObject self, IRubyObject _mask, Block block)
    • pending_interrupt_p_s

      public static IRubyObject pending_interrupt_p_s(ThreadContext context, IRubyObject self)
    • pending_interrupt_p_s

      public static IRubyObject pending_interrupt_p_s(ThreadContext context, IRubyObject self, IRubyObject err)
    • pending_interrupt_p

      public IRubyObject pending_interrupt_p(ThreadContext context)
    • pending_interrupt_p

      public IRubyObject pending_interrupt_p(ThreadContext context, IRubyObject err)
    • setName

      @Deprecated(since="10.0") public IRubyObject setName(IRubyObject name)
      Deprecated.
    • setName

      public IRubyObject setName(ThreadContext context, IRubyObject name)
    • getName

      @Deprecated(since="10.0") public IRubyObject getName()
      Deprecated.
    • getName

      public IRubyObject getName(ThreadContext context)
    • current

      public static RubyThread current(IRubyObject recv)
    • main

      public static RubyThread main(IRubyObject recv)
    • pass

      public static IRubyObject pass(ThreadContext context, IRubyObject recv)
    • list

      public static RubyArray list(IRubyObject recv)
    • add_trace_func

      public IRubyObject add_trace_func(ThreadContext context, IRubyObject trace_func, Block block)
    • add_trace_func

      public static IRubyObject add_trace_func(ThreadContext context, IRubyObject recv, IRubyObject trace_func, Block block)
    • set_trace_func

      public IRubyObject set_trace_func(ThreadContext context, IRubyObject trace_func, Block block)
    • clearFiberLocals

      public void clearFiberLocals()
      Clear the fiber local variable storage for this thread. Meant for Java consumers when reusing threads (e.g. during thread pooling).
      See Also:
    • clearThreadLocals

      public void clearThreadLocals()
      Clear the thread local variable storage for this thread. Meant for Java consumers when reusing threads (e.g. during thread pooling).
      See Also:
    • getContextVariables

      public final Map<Object,IRubyObject> getContextVariables()
      Specified by:
      getContextVariables in interface ExecutionContext
    • isAlive

      public boolean isAlive()
    • isAdopted

      public boolean isAdopted()
    • fetch

      public IRubyObject fetch(ThreadContext context, IRubyObject key, Block block)
    • fetch

      public IRubyObject fetch(ThreadContext context, IRubyObject key, IRubyObject _default, Block block)
    • op_aref

      public IRubyObject op_aref(ThreadContext context, IRubyObject key)
    • op_aset

      public IRubyObject op_aset(ThreadContext context, IRubyObject key, IRubyObject value)
    • key_p

      public RubyBoolean key_p(ThreadContext context, IRubyObject key)
    • keys

      public RubyArray keys()
    • thread_variable_p

      public IRubyObject thread_variable_p(ThreadContext context, IRubyObject key)
    • thread_variable_get

      public IRubyObject thread_variable_get(ThreadContext context, IRubyObject key)
    • thread_variable_set

      public IRubyObject thread_variable_set(ThreadContext context, IRubyObject key, IRubyObject value)
    • thread_variables

      public IRubyObject thread_variables(ThreadContext context)
    • isAbortOnException

      public boolean isAbortOnException()
    • setAbortOnException

      public void setAbortOnException(boolean abortOnException)
    • abort_on_exception

      public RubyBoolean abort_on_exception(ThreadContext context)
    • abort_on_exception_set

      public IRubyObject abort_on_exception_set(IRubyObject val)
    • abort_on_exception

      public static RubyBoolean abort_on_exception(ThreadContext context, IRubyObject recv)
      Returns the status of the global ``abort on exception'' condition. The default is false. When set to true, will cause all threads to abort (the process will exit(0)) if an exception is raised in any thread. See also Thread.abort_on_exception= .
    • abort_on_exception_set

      public static IRubyObject abort_on_exception_set(ThreadContext context, IRubyObject recv, IRubyObject value)
    • alive_p

      public RubyBoolean alive_p(ThreadContext context)
    • join

      public IRubyObject join(ThreadContext context)
    • join

      public IRubyObject join(ThreadContext context, IRubyObject timeout)
    • value

      public IRubyObject value(ThreadContext context)
    • group

      public IRubyObject group()
    • inspect

      public RubyString inspect(ThreadContext context)
      Description copied from class: RubyBasicObject
      Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string. [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]" Time.new.inspect #=> "Wed Apr 09 08:54:39 CDT 2003"
      Specified by:
      inspect in interface IRubyObject
      Overrides:
      inspect in class RubyBasicObject
    • stop

      public static IRubyObject stop(ThreadContext context, IRubyObject receiver)
    • kill

      public static IRubyObject kill(IRubyObject recv, IRubyObject rubyThread, Block block)
    • exit

      public static IRubyObject exit(IRubyObject receiver, Block block)
    • stop_p

      public RubyBoolean stop_p(ThreadContext context)
    • stop_p

      @Deprecated public RubyBoolean stop_p()
      Deprecated.
    • wakeup

      public RubyThread wakeup()
    • priority

      @Deprecated(since="10.0") public RubyFixnum priority()
      Deprecated.
    • priority

      public RubyFixnum priority(ThreadContext context)
    • priority_set

      @Deprecated(since="10.0") public IRubyObject priority_set(IRubyObject priority)
      Deprecated.
    • priority_set

      public IRubyObject priority_set(ThreadContext context, IRubyObject priority)
    • javaPriorityToRubyPriority

      public static int javaPriorityToRubyPriority(int javaPriority)
    • rubyPriorityToJavaPriority

      public static int rubyPriorityToJavaPriority(int rubyPriority)
    • raise

      public final IRubyObject raise(IRubyObject exception)
      Simplified utility method for just raising an existing exception in this thread.
      Parameters:
      exception - the exception to raise
      Returns:
      this thread
    • raise

      public final IRubyObject raise(IRubyObject exception, RubyString message)
      Simplified utility method for just raising an existing exception in this thread.
      Parameters:
      exception - the exception to raise
      message - the message to use
      Returns:
      this thread
    • raise

      public IRubyObject raise(ThreadContext context, IRubyObject[] args, Block block)
    • native_thread_id

      public IRubyObject native_thread_id(ThreadContext context)
    • prepareRaiseException

      public static IRubyObject prepareRaiseException(ThreadContext context, IRubyObject[] args)
    • run

      public IRubyObject run()
    • sleep

      public boolean sleep(long milliseconds) throws InterruptedException
      Sleep the current thread for milliseconds, waking up on any thread interrupts.
      Parameters:
      milliseconds - Number of milliseconds to sleep. Zero sleeps forever.
      Throws:
      InterruptedException
    • sleep

      public boolean sleep(long milliseconds, long nanoseconds) throws InterruptedException
      Sleep the current thread for milliseconds + nanoseconds, waking up on any thread interrupts. We can never be sure if a wait will finish because of a Java "spurious wakeup". So if we explicitly wakeup and we wait less than requested amount we will return false. We will return true if we sleep right amount or less than right amount via spurious wakeup.
      Parameters:
      milliseconds - Number of milliseconds to sleep. Combined with nanoseconds, zero sleeps forever.
      nanoseconds - Number of nanoseconds to sleep. Combined with milliseconds, zero sleeps forever.
      Throws:
      InterruptedException
    • status

      public IRubyObject status()
    • status

      public IRubyObject status(ThreadContext context)
    • each_caller_location

      public static IRubyObject each_caller_location(ThreadContext context, IRubyObject recv, Block block)
    • getExitingException

      public Throwable getExitingException()
      Returns:
      existing exception or null if terminated normally
    • executeBlockingTask

      @Deprecated public void executeBlockingTask(RubyThread.BlockingTask task) throws InterruptedException
      Deprecated.
      Throws:
      InterruptedException
    • executeTaskBlocking

      public <Data, Return> Return executeTaskBlocking(ThreadContext context, Data data, RubyThread.Task<Data,Return> task) throws InterruptedException
      Throws:
      InterruptedException
    • executeTask

      public <Data, Return> Return executeTask(ThreadContext context, Data data, RubyThread.Task<Data,Return> task) throws InterruptedException
      Throws:
      InterruptedException
    • executeTaskBlocking

      public <Data, Return> Return executeTaskBlocking(ThreadContext context, Data data, RubyThread.Status status, RubyThread.Task<Data,Return> task) throws InterruptedException
      Throws:
      InterruptedException
    • executeTask

      public <Data, Return> Return executeTask(ThreadContext context, Data data, RubyThread.Status status, RubyThread.Task<Data,Return> task) throws InterruptedException
      Throws:
      InterruptedException
    • executeReadWrite

      public <Data> int executeReadWrite(ThreadContext context, Data data, byte[] bytes, int start, int length, RubyThread.ReadWrite<Data> task) throws InterruptedException
      Execute an interruptible read or write operation with the given byte range and data object.
      Type Parameters:
      Data - the type of the data object
      Parameters:
      context - the current context
      data - a data object
      bytes - the bytes to write
      start - start range of bytes to write
      length - length of bytes to write
      task - the write task
      Returns:
      the number of bytes written
      Throws:
      InterruptedException
    • executeReadWrite

      public <Data> int executeReadWrite(ThreadContext context, Data data, ByteBuffer bytes, int start, int length, RubyThread.ReadWrite<Data> task) throws InterruptedException
      Throws:
      InterruptedException
    • executeRegexp

      public <Data> int executeRegexp(ThreadContext context, org.joni.Matcher matcher, int start, int range, int option, RubyThread.RegexMatch task) throws InterruptedException
      Execute an interruptible regexp operation with the given function and bytess.
      Type Parameters:
      Data -
      Parameters:
      context -
      matcher -
      start -
      range -
      option -
      task -
      Returns:
      ""
      Throws:
      InterruptedException - when interrupted
    • enterSleep

      public void enterSleep()
    • exitSleep

      public void exitSleep()
    • kill

      public IRubyObject kill()
    • dieFromFinalizer

      public void dieFromFinalizer()
      Used for finalizers that need to kill a Ruby thread. Finalizers run in a VM thread to which we do not want to attach a ThreadContext and within which we do not want to check for Ruby thread events. This mechanism goes directly to mail delivery, bypassing all Ruby Thread-related steps.
    • backtrace

      public IRubyObject backtrace(ThreadContext context)
    • backtrace

      public IRubyObject backtrace(ThreadContext context, IRubyObject level)
    • backtrace

      public IRubyObject backtrace(ThreadContext context, IRubyObject level, IRubyObject length)
    • backtrace_locations

      public IRubyObject backtrace_locations(ThreadContext context)
    • backtrace_locations

      public IRubyObject backtrace_locations(ThreadContext context, IRubyObject level)
    • backtrace_locations

      public IRubyObject backtrace_locations(ThreadContext context, IRubyObject level, IRubyObject length)
    • isReportOnException

      public boolean isReportOnException()
    • setReportOnException

      public void setReportOnException(boolean reportOnException)
    • report_on_exception_set

      public IRubyObject report_on_exception_set(ThreadContext context, IRubyObject state)
    • report_on_exception

      public IRubyObject report_on_exception(ThreadContext context)
    • report_on_exception_set

      public static IRubyObject report_on_exception_set(ThreadContext context, IRubyObject self, IRubyObject state)
    • report_on_exception

      public static IRubyObject report_on_exception(ThreadContext context, IRubyObject self)
    • javaBacktrace

      public StackTraceElement[] javaBacktrace()
    • exceptionRaised

      public void exceptionRaised(RaiseException exception)
    • printReportExceptionWarning

      protected void printReportExceptionWarning()
    • exceptionRaised

      public void exceptionRaised(Throwable throwable)
      For handling all exceptions bubbling out of threads
      Parameters:
      throwable -
    • mainThread

      public static RubyThread mainThread(IRubyObject receiver)
    • select

      public boolean select(RubyIO io, int ops)
      Perform an interruptible select operation on the given channel and fptr, waiting for the requested operations or the given timeout.
      Parameters:
      io - the RubyIO that contains the channel, for managing blocked threads list.
      ops - the operations to wait for, from SelectionKey.
      Returns:
      true if the IO's channel became ready for the requested operations, false if it was not selectable.
    • select

      public boolean select(RubyIO io, int ops, long timeout)
      Perform an interruptible select operation on the given channel and fptr, waiting for the requested operations or the given timeout.
      Parameters:
      io - the RubyIO that contains the channel, for managing blocked threads list.
      ops - the operations to wait for, from SelectionKey.
      timeout - a timeout in ms to limit the select. Less than zero selects forever, zero selects and returns ready channels or nothing immediately, and greater than zero selects for at most that many ms.
      Returns:
      true if the IO's channel became ready for the requested operations, false if it timed out or was not selectable.
    • select

      public boolean select(Channel channel, OpenFile fptr, int ops)
      Perform an interruptible select operation on the given channel and fptr, waiting for the requested operations.
      Parameters:
      channel - the channel to perform a select against. If this is not a selectable channel, then this method will just return true.
      fptr - the fptr that contains the channel, for managing blocked threads list.
      ops - the operations to wait for, from SelectionKey.
      Returns:
      true if the channel became ready for the requested operations, false if it was not selectable.
    • select

      public boolean select(Channel channel, RubyIO io, int ops)
      Perform an interruptible select operation on the given channel and fptr, waiting for the requested operations.
      Parameters:
      channel - the channel to perform a select against. If this is not a selectable channel, then this method will just return true.
      io - the RubyIO that contains the channel, for managing blocked threads list.
      ops - the operations to wait for, from SelectionKey.
      Returns:
      true if the channel became ready for the requested operations, false if it was not selectable.
    • select

      public boolean select(Channel channel, RubyIO io, int ops, long timeout)
      Perform an interruptible select operation on the given channel and fptr, waiting for the requested operations or the given timeout.
      Parameters:
      channel - the channel to perform a select against. If this is not a selectable channel, then this method will just return true.
      io - the RubyIO that contains the channel, for managing blocked threads list.
      ops - the operations to wait for, from SelectionKey.
      timeout - a timeout in ms to limit the select. Less than zero selects forever, zero selects and returns ready channels or nothing immediately, and greater than zero selects for at most that many ms.
      Returns:
      true if the channel became ready for the requested operations, false if it timed out or was not selectable.
    • select

      public boolean select(Channel channel, OpenFile fptr, int ops, long timeout)
      Perform an interruptible select operation on the given channel and fptr, waiting for the requested operations or the given timeout.
      Parameters:
      channel - the channel to perform a select against. If this is not a selectable channel, then this method will just return true.
      fptr - the fptr that contains the channel, for managing blocked threads list.
      ops - the operations to wait for, from SelectionKey.
      timeout - a timeout in ms to limit the select. Less than zero selects forever, zero selects and returns ready channels or nothing immediately, and greater than zero selects for at most that many ms.
      Returns:
      true if the channel became ready for the requested operations, false if it timed out or was not selectable.
    • interrupt

      public void interrupt()
    • setInterrupt

      public void setInterrupt()
      Set the pending interrupt flag. CRuby: RB_VM_SET_INTERRUPT/
    • waitForIO

      public boolean waitForIO(ThreadContext context, RubyIO io, int ops)
    • beforeBlockingCall

      public void beforeBlockingCall(ThreadContext context)
    • beforeBlockingCall

      @Deprecated public void beforeBlockingCall()
      Deprecated.
    • afterBlockingCall

      public void afterBlockingCall()
    • wait_timeout

      public boolean wait_timeout(IRubyObject o, Double timeout) throws InterruptedException
      Throws:
      InterruptedException
    • getThreadGroup

      public RubyThreadGroup getThreadGroup()
    • equals

      public boolean equals(Object obj)
      Description copied from class: RubyObject
      This override does not do a "checked" dispatch.
      Overrides:
      equals in class RubyObject
      Parameters:
      obj - object to compare
      Returns:
      true if equals
      See Also:
    • hashCode

      public int hashCode()
      Description copied from class: RubyObject
      This override does not do "checked" dispatch since Object usually has #hash defined.
      Overrides:
      hashCode in class RubyObject
      Returns:
      the hash code
      See Also:
    • toString

      public String toString()
      Description copied from class: RubyObject
      The default toString method is just a wrapper that calls the Ruby "to_s" method.
      Overrides:
      toString in class RubyObject
      Returns:
      string representation
    • lock

      public void lock(Lock lock)
      Acquire the given lock, holding a reference to it for cleanup on thread termination.
      Parameters:
      lock - the lock to acquire, released on thread termination
    • lockInterruptibly

      public void lockInterruptibly(Lock lock) throws InterruptedException
      Acquire the given lock interruptibly, holding a reference to it for cleanup on thread termination.
      Parameters:
      lock - the lock to acquire, released on thread termination
      Throws:
      InterruptedException - if the lock acquisition is interrupted
    • tryLock

      public boolean tryLock(Lock lock)
      Try to acquire the given lock, adding it to a list of held locks for cleanup on thread termination if it is acquired. Return immediately if the lock cannot be acquired.
      Parameters:
      lock - the lock to acquire, released on thread termination
    • unlock

      public void unlock(Lock lock)
      Release the given lock and remove it from the list of locks to be released on thread termination.
      Parameters:
      lock - the lock to release and dereferences
    • unlockAll

      public void unlockAll()
      Release all locks held.
    • sleep

      public void sleep(Lock lock) throws InterruptedException
      Release lock and sleep.
      Throws:
      InterruptedException
    • sleep

      public void sleep(Lock lock, long millis) throws InterruptedException
      Release lock and sleep for the specified number of milliseconds.
      Throws:
      InterruptedException
    • toJava

      public <T> T toJava(Class<T> target)
      Customized for retrieving a Java thread from a Ruby one.
      Specified by:
      toJava in interface IRubyObject
      Overrides:
      toJava in class RubyBasicObject
      Type Parameters:
      T - type
      Parameters:
      target - The target type to which the object should be converted (e.g. java.lang.Thread.class).
      Returns:
      java type
      Since:
      9.4
      See Also:
    • uninterruptible

      public static <StateType> IRubyObject uninterruptible(ThreadContext context, StateType state, BiFunction<ThreadContext,StateType,IRubyObject> f)
      Run the provided BiFunction without allowing for any cross-thread interrupts (equivalent to calling handle_interrupt(ThreadContext, IRubyObject, IRubyObject, Block) with Object => :never. MRI: rb_uninterruptible
      Parameters:
      context - the current context
      f - the bifunction to execute
      Returns:
      return value of f.apply.
    • setFiberScheduler

      @Deprecated(since="10.0") public IRubyObject setFiberScheduler(IRubyObject scheduler)
      Deprecated.
    • setFiberScheduler

      public IRubyObject setFiberScheduler(ThreadContext context, IRubyObject scheduler)
      Set the scheduler for the current thread. MRI: rb_fiber_scheduler_set
    • getScheduler

      public IRubyObject getScheduler()
    • getSchedulerCurrent

      public IRubyObject getSchedulerCurrent()
    • incrementBlocking

      public void incrementBlocking()
    • decrementBlocking

      public void decrementBlocking()
    • isBlocking

      public boolean isBlocking()
    • pending_interrupt_p

      @Deprecated public IRubyObject pending_interrupt_p(ThreadContext context, IRubyObject[] args)
      Deprecated.
    • pending_interrupt_p

      @Deprecated public static IRubyObject pending_interrupt_p(ThreadContext context, IRubyObject self, IRubyObject[] args)
      Deprecated.
    • alive_p

      @Deprecated public RubyBoolean alive_p()
      Deprecated.
    • value

      @Deprecated public IRubyObject value()
      Deprecated.
    • join

      @Deprecated public IRubyObject join(ThreadContext context, IRubyObject[] args)
      Deprecated.
    • op_aset

      @Deprecated public IRubyObject op_aset(IRubyObject key, IRubyObject value)
      Deprecated.