HandlerThread
open class HandlerThread : Thread
A Thread that has a Looper. The Looper can then be used to create Handlers. Just like with a regular Thread, start() must still be called.
Use this class only if you must work with the Handler API and need a Thread to do the handling on that is not an existing Looper thread, such as Looper.getMainLooper(). Otherwise, prefer java.util.concurrent.Executor or java.util.concurrent.ExecutorService, or Kotlin coroutines.
Note that many APIs that required a Handler in older SDK versions offer a newer alternative that accepts an java.util.concurrent.Executor instead. Always prefer to use the newer API if available.
Alternatives to HandlerThread
java.util.concurrent.Executors offer more flexibility with regards to threading. Work submitted to an java.util.concurrent.Executor can be set to run on another thread, on one of several threads from a static or dynamic pool, or on the caller's thread, depending on your needs.
{link @link java.util.concurrent.Executor} offers a simpler API that is easier to use compared to Handler. {link @link java.util.concurrent.ExecutorService} offers the richer java.util.concurrent.Future API, which you can use to monitor task status, cancel tasks, propagate exceptions, and chain multiple pending tasks.
{link @link java.util.concurrent.Executors} is a factory for various java.util.concurrent.Executors that meet common concurrency needs. These java.util.concurrent.Executors use work queues that offer better concurrency and reduced contention than HandlerThread.
On Kotlin, coroutines may be used to handle concurrency.
Apps that use HandlerThread may encounter the following performance issues:
- Excessive thread creation: A
HandlerThread is a java.lang.Thread. Every system thread costs some resident memory, whether it is working or if it's idle. If your app has a large number of HandlerThreads each dedicated to a single type of task, rather than for instance a java.util.concurrent.ThreadPoolExecutor that can grow and shrink in size according to demand, then the additional idle HandlerThreads will be wasting memory.
- Lock contention:
HandlerThread uses a Looper which in turn uses a MessageQueue. MessageQueue uses a single lock to synchronize access to its underlying queue. Any threads attempting to enqueue messages at the same time, and the HandlerThread itself when attempting to dequeue the next message to handle, will block each other.
- Priority inversion: A high-priority
HandlerThread can become blocked by a lower-priority thread, for instance if the former is trying to enqueue a message while the latter is trying to dequeue the next message to handle, or vice versa.
The best way to avoid these issues is to use
java.util.concurrent.Executors or
Kotlin coroutines instead of
HandlerThread.
Summary
| Public constructors |
|
|
|
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 |
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
|
| Protected methods |
| open Unit |
Call back method that can be explicitly overridden if needed to execute some setup before Looper loops.
|
| Inherited functions |
From class Thread
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 InterruptibleChannel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.
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).
|
Boolean |
isAlive()
Tests if this thread is alive. A thread is alive if it has been started and has not yet terminated.
|
Boolean |
isDaemon()
Tests if this thread is a daemon thread.
|
Boolean |
| |