# <cfthread>

The `cfthread` tag enables concurrent execution through thread management in your CFML application.
 			
Threads are independent streams of code execution that allow you to perform multiple operations simultaneously, improving application performance and responsiveness. You can use this tag to:

* **Create** new threads with custom processing
* **Join** multiple threads together, synchronizing their execution
* **Sleep** the current thread to pause execution
* **Terminate** threads that need to be stopped immediately
* **Interrupt** threads, allowing for cooperative stopping with resource cleanup. (**Introduced:** 7.0.0.120)
    
Each thread gets its own isolated variable scope (`thread`) that persists across the thread's lifetime and can be accessed from other parts of your application.

You can pass in any additional attributes you need to, these are then available within the thread,
in the `attributes` scope, which is useful for passing data into the thread.

In Lucee these attributes are passed **by reference**, unlike other CFML engines.

If you are using thread in cfscript, you can also access these via the `arguments` scope,
but this is not recommended or compatible with other CFML engines.

Each thread has it's own unique set of debugging logs, which will not show up in the main pages, normal debugging report.

You can access this debugging data, inside the thread using `<cfadmin action="getDebugData" returnVariable="data">`.

This tag **may** have a body.
This tag is also supported within [<cfscript>](script.md)

```
<cfthread
    action=join|run|sleep|terminate|interrupt
    type=daemon|task
    retryInterval=any
    duration=number
    name=string
    priority=string
    timeout=number
    throwOnError=boolean
><!--- body ---></cfthread>
```

# Attributes

| Attribute | Type | Required | Description | Default |
|-----------|------|----------|-------------|---------|
| action | string | No | Specifies the operation to perform on the thread. Options include: * **run** (default): Creates a new thread and begins execution immediately. The thread executes the code contained within the tag body. * **join**: Synchronizes the current thread with one or more target threads, pausing execution until the specified threads complete or a timeout occurs. This enables coordinated workflows where operations depend on the results of multiple threads. * **sleep**: Temporarily suspends the current thread's execution for the specified duration in milliseconds. This action is useful for rate-limiting, implementing delays, or yielding processing time to other threads without creating full thread dependencies. * **terminate**: Forcibly stops the specified thread's execution immediately. This is a non-cooperative shutdown that may leave resources in an inconsistent state. When terminated, the thread scope will include an `ERROR` metadata structure with termination details. * **interrupt**: Sets the interrupt status flag on the specified thread, requesting cooperative termination. If the thread is blocked in a `ThreadJoin`, `sleep`, or I/O operation, it will receive an `InterruptedException` and its interrupt status will be cleared. The thread can then perform cleanup operations before stopping, making this safer than `terminate` for most scenarios. (**Introduced**: 7.0.0.120) | run |
| type | string | No | Defines the thread execution model: * **daemon** (default): Executes as a daemon thread of the current thread. Daemon threads do not prevent the application from shutting down when all non-daemon threads have completed. * **task**: Executed by the Lucee task manager, which provides additional robustness features like retry mechanisms. Task threads are ideal for asynchronous operations that should continue even if the user request completes. | daemon |
| retryInterval | any | No | When `type="task"`, this attribute defines an execution plan for automatic retry attempts when thread execution fails. You can specify either a single retry rule or multiple rules as an array. A single rule specifies the interval between retries and the number of retry attempts with a structure containing `interval` and `tries` keys. The `interval` is a timespan value defining the waiting period between retries, and `tries` is the number of retry attempts. Example: ```luceescript #{interval:createTimeSpan(0,0,0,5),tries:5}# ``` Multiple rules can be defined as an array of structures, each containing `interval` and `tries` keys. This allows for implementing progressive retry strategies with different intervals for different phases of the retry process. Example: ```luceescript #[{interval:createTimeSpan(0,0,0,5),tries:5},{interval:createTimeSpan(0,0,0,10),tries:5}]# ``` *Alias: retryintervall* |  |
| duration | number | No | The number of milliseconds to suspend thread processing when using `action="sleep"`. This parameter is required for the sleep action. Typical use cases include adding delays between operations, implementing rate limiting or throttling, and simulating latency for testing purposes. |  |
| name | string | No | Specifies the target thread identifier(s). The usage depends on the `action` attribute: * With `action="run"`: Defines the name to identify the new thread being created. This name becomes the key in the `thread` scope and must be unique within the application. * With `action="join"`: Specifies which thread(s) the current thread should wait for. To join multiple threads, provide a comma-delimited list of thread names. * With `action="terminate"` or `action="interrupt"`: Identifies the thread(s) to stop or interrupt. Thread names should be descriptive of their purpose and follow a consistent naming convention for maintainability. *Alias: names* |  |
| priority | string | No | Sets the execution priority level for the thread when using `action="run"`. Valid values are: * **HIGH**: Thread receives more CPU time, suitable for critical operations * **NORMAL**: Standard priority level (default) * **LOW**: Thread receives less CPU time, suitable for background operations Priority affects thread scheduling by the JVM but does not guarantee execution order. Higher priority threads generally get more processing time than lower priority ones, but this depends on the JVM implementation and system load. Note that page-level code (outside of `cfthread` tags) always executes at `NORMAL` priority. |  |
| timeout | number | No | When using `action="join"`, specifies the maximum time in milliseconds that the current thread will wait for the joined thread(s) to complete. * If set to `0` (default): The current thread will wait indefinitely until all joining threads finish. * If set to any positive number: The current thread will resume after the specified timeout, even if joined threads haven't completed. This attribute prevents deadlocks and allows for graceful timeout handling in multi-threaded operations. When the current thread is the page thread, the page continues waiting until either the threads complete or the timeout expires, regardless of page timeout settings. |  |
| throwOnError | boolean | No | Only applicable with `action="join"`. Determines whether exceptions thrown in joined threads should propagate to the joining thread. * When `true`: If any of the joined threads have encountered errors, the first error found will be thrown as an exception in the current thread. This allows for easier error detection by propagating errors up the call stack. * When `false` (default): Errors in joined threads remain isolated in their respective thread scopes and won't affect the current thread's execution. You must explicitly check the thread status to identify errors. This attribute is useful for implementing fail-fast behavior in situations where thread errors should immediately stop dependent operations. | false |

# Examples

<https://www.youtube.com/watch?v=oGUZRrcg9KE>





## Related System Properties / Environment Variables

- [LUCEE_TAG_POPULATE_LOCALSCOPE](../../recipes/environment-variables-system-properties.md#lucee_tag_populate_localscope) - Controls whether tags like cflock and cfquery populate their default result variables to local scope when inside a function. When `true`, variables go to local scope. When `false`, restores pre LDEV-5416 behavior where variables go to variables scope
  ***Type:** boolean, **Default:** true, **Introduced:** 7.0.1.13*
- [LUCEE_TASKS_LIMIT](../../recipes/environment-variables-system-properties.md#lucee_tasks_limit) - Defines the maximum number of elements that can be stored in the cfthread scope. Once this limit is reached, the oldest entries are automatically removed to make room for new ones
  ***Type:** numeric, **Default:** true, **Introduced:** 6.0.2.10*
- [LUCEE_THREADS_MAXDEFAULT](../../recipes/environment-variables-system-properties.md#lucee_threads_maxdefault) - Sets the maximum number of parallel threads
  ***Type:** numeric, **Default:** true*



# Categories

[Threads](../../categories/thread.md)

# See Also

[IsInThread()](../functions/isinthread.md), [Function Listeners](../../recipes/function-listeners.md), [ThreadData()](../functions/threaddata.md), [ThreadInterrupt()](../functions/threadinterrupt.md), [ThreadJoin()](../functions/threadjoin.md), [ThreadTerminate()](../functions/threadterminate.md), [<cftimeout>](timeout.md), [Complete Guide to Threading in Lucee](../../recipes/thread-usage.md), [Thread Tasks](../../recipes/thread-task.md)