Added in API level 1

HandlerThread


open class HandlerThread : Thread

A Thread that has a Looper. The Looper can then be used to create Handlers.

Note that just like with a regular Thread, start() must still be called.

Summary

Inherited constants
Int MAX_PRIORITY

The maximum priority that a thread can have.

Int MIN_PRIORITY

The minimum priority that a thread can have.

Int NORM_PRIORITY

The default priority that is assigned to a thread.

Public constructors

HandlerThread(name: String!, priority: Int)

Constructs a HandlerThread.

Public methods
open Looper!

This method returns the Looper associated with this thread.

open Int

Returns the identifier of this thread.

open Boolean

Quits the handler thread's looper.

open Boolean

Quits the handler thread's looper safely.

open Unit
run()

Protected methods
open Unit

Call back method that can be explicitly overridden if needed to execute some setup before Looper loops.

Inherited functions
Int activeCount()

Returns an estimate of the number of active threads in the current thread's thread group and its subgroups. Recursively iterates over all subgroups in the current thread's thread group.

The value returned is only an estimate because the number of threads may change dynamically while this method traverses internal data structures, and might be affected by the presence of certain system threads. This method is intended primarily for debugging and monitoring purposes.

Unit checkAccess()

Determines if the currently running thread has permission to modify this thread.

If there is a security manager, its checkAccess method is called with this thread as its argument. This may result in throwing a SecurityException.

Any clone()

Throws CloneNotSupportedException as a Thread can not be meaningfully cloned. Construct a new Thread instead.

Thread currentThread()

Returns a reference to the currently executing thread object.

Unit dumpStack()

Prints a stack trace of the current thread to the standard error stream. This method is used only for debugging.

Int enumerate(tarray: Array<Thread!>!)

Copies into the specified array every active thread in the current thread's thread group and its subgroups. This method simply invokes the java.lang.ThreadGroup#enumerate(Thread[]) method of the current thread's thread group.

An application might use the activeCount method to get an estimate of how big the array should be, however if the array is too short to hold all the threads, the extra threads are silently ignored. If it is critical to obtain every active thread in the current thread's thread group and its subgroups, the invoker should verify that the returned int value is strictly less than the length of tarray.

Due to the inherent race condition in this method, it is recommended that the method only be used for debugging and monitoring purposes.

MutableMap<Thread!, Array<StackTraceElement!>!> getAllStackTraces()

Returns a map of stack traces for all live threads. The map keys are threads and each map value is an array of StackTraceElement that represents the stack dump of the corresponding Thread. The returned stack traces are in the format specified for the getStackTrace method.

The threads may be executing while this method is called. The stack trace of each thread only represents a snapshot and each stack trace may be obtained at different time. A zero-length array will be returned in the map value if the virtual machine has no stack trace information about a thread.

ClassLoader? getContextClassLoader()

Returns the context ClassLoader for this thread. The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application.

Thread.UncaughtExceptionHandler? getDefaultUncaughtExceptionHandler()

Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception. If the returned value is null, there is no default.

Long getId()

Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.

String getName()

Returns this thread's name.

Int getPriority()

Returns this thread's priority.

Array<StackTraceElement!> getStackTrace()

Returns an array of stack trace elements representing the stack dump of this thread. This method will return a zero-length array if this thread 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.

If there is a security manager, and this thread is not the current thread, then the security manager's checkPermission method is called with a RuntimePermission("getStackTrace") permission to see if it's ok to get the stack trace.

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 thread is permitted to return a zero-length array from this method.

Thread.State getState()

Returns the state of this thread. This method is designed for use in monitoring of the system state, not for synchronization control.

ThreadGroup? getThreadGroup()

Returns the thread group to which this thread belongs. This method returns null if this thread has died (been stopped).

Thread.UncaughtExceptionHandler? getUncaughtExceptionHandler()

Returns the handler invoked when this thread abruptly terminates due to an uncaught exception. If this thread has not had an uncaught exception handler explicitly set then this thread's ThreadGroup object is returned, unless this thread has terminated, in which case null is returned.

Boolean holdsLock(obj: Any)

Returns true if and only if the current thread holds the monitor lock on the specified object.

This method is designed to allow a program to assert that the current thread already holds a specified lock:

assert Thread.holdsLock(obj);
  

Unit interrupt()

Interrupts this thread.

Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long,int), sleep(long), or sleep(long,int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a .

If this thread is blocked in a java.nio.channels.Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

Interrupting a thread that is not alive need not have any effect.

Boolean interrupted()

Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.

Boolean isAlive()

Tests if this thread is alive. A thread is alive if it has been started and has not yet died.

Boolean isDaemon()

Tests if this thread is a daemon thread.

Boolean isInterrupted()

Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.

Boolean isVirtual()

Returns true if this thread is a virtual thread. A virtual thread is scheduled by the Java virtual machine rather than the operating system.

Unit join()

Waits for this thread to die.

An invocation of this method behaves in exactly the same way as the invocation

join(0)

Unit join(millis: Long)

Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Unit join(millis: Long, nanos: Int)

Waits at most millis milliseconds plus nanos nanoseconds for this thread to die. If both arguments are 0, it means to wait forever.

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Unit onSpinWait()

Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities. By invoking this method within each iteration of a spin-wait loop construct, the calling thread indicates to the runtime that it is busy-waiting. The runtime may take action to improve the performance of invoking spin-wait loop constructions.

Unit setContextClassLoader(cl: ClassLoader?)

Sets the context ClassLoader for this Thread. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader, through getContextClassLoader, to code running in the thread when loading classes and resources.

If a security manager is present, its checkPermission method is invoked with a RuntimePermission("setContextClassLoader") permission to see if setting the context ClassLoader is permitted.

Unit setDaemon(on: Boolean)

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

This method must be invoked before the thread is started.

Unit setDefaultUncaughtExceptionHandler(eh: Thread.UncaughtExceptionHandler?)

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Uncaught exception handling is controlled first by the thread, then by the thread's ThreadGroup object and finally by the default uncaught exception handler. If the thread does not have an explicit uncaught exception handler set, and the thread's thread group (including parent thread groups) does not specialize its uncaughtException method, then the default handler's uncaughtException method will be invoked.

By setting the default uncaught exception handler, an application can change the way in which uncaught exceptions are handled (such as logging to a specific device, or file) for those threads that would already accept whatever "default" behavior the system provided.

Note that the default uncaught exception handler should not usually defer to the thread's ThreadGroup object, as that could cause infinite recursion.

Unit setName(name: String)

Changes the name of this thread to be equal to the argument name.

First the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException.

Unit setPriority(newPriority: Int)

Changes the priority of this thread.

First the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException.

Otherwise, the priority of this thread is set to the smaller of the specified newPriority and the maximum permitted priority of the thread's thread group.

Unit setUncaughtExceptionHandler(eh: Thread.UncaughtExceptionHandler?)

Set the handler invoked when this thread abruptly terminates due to an uncaught exception.

A thread can take full control of how it responds to uncaught exceptions by having its uncaught exception handler explicitly set. If no such handler is set then the thread's ThreadGroup object acts as its handler.

Unit sleep(millis: Long)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Unit sleep(millis: Long, nanos: Int)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Unit start()

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Unit stop()

Throws UnsupportedOperationException.

Long threadId()

Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime.

String toString()

Returns a string representation of this thread, including the thread's name, priority, and thread group.

Unit yield()

A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.

It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

Public constructors

HandlerThread

Added in API level 1
HandlerThread(name: String!)

HandlerThread

Added in API level 1
HandlerThread(
    name: String!,
    priority: Int)

Constructs a HandlerThread.

Parameters
name String!:
priority Int: The priority to run the thread at. The value supplied must be from android.os.Process and not from java.lang.Thread.

Public methods

getLooper

Added in API level 1
open fun getLooper(): Looper!

This method returns the Looper associated with this thread. If this thread not been started or for any reason isAlive() returns false, this method will return null. If this thread has been started, this method will block until the looper has been initialized.

Return
Looper! The looper.

getThreadId

Added in API level 1
open fun getThreadId(): Int

Returns the identifier of this thread. See Process.myTid().

quit

Added in API level 5
open fun quit(): Boolean

Quits the handler thread's looper.

Causes the handler thread's looper to terminate without processing any more messages in the message queue.

Any attempt to post messages to the queue after the looper is asked to quit will fail. For example, the Handler.sendMessage(Message) method will return false.

Using this method may be unsafe because some messages may not be delivered before the looper terminates. Consider using quitSafely instead to ensure that all pending work is completed in an orderly manner.

Return
Boolean True if the looper looper has been asked to quit or false if the thread had not yet started running.

See Also

quitSafely

Added in API level 18
open fun quitSafely(): Boolean

Quits the handler thread's looper safely.

Causes the handler thread's looper to terminate as soon as all remaining messages in the message queue that are already due to be delivered have been handled. Pending delayed messages with due times in the future will not be delivered.

Any attempt to post messages to the queue after the looper is asked to quit will fail. For example, the Handler.sendMessage(Message) method will return false.

If the thread has not been started or has finished (that is if getLooper returns null), then false is returned. Otherwise the looper is asked to quit and true is returned.

Return
Boolean True if the looper looper has been asked to quit or false if the thread had not yet started running.

run

Added in API level 1
open fun run(): Unit

Protected methods

onLooperPrepared

Added in API level 1
protected open fun onLooperPrepared(): Unit

Call back method that can be explicitly overridden if needed to execute some setup before Looper loops.