Threads are independent streams of execution. Multiple threads on a page or CFC can execute simultaneously and asynchronously, letting you perform asynchronous processing in CFML.
Threads are useful for two broad types of activities:
- When multiple actions can occur simultaneously
- When you do not have to wait for one action to complete before starting the next action
Some typical uses for threads include the following examples:
- An application that aggregates information from multiple external sources, that takes significant time to respond, has the code that gets information from each source in a separate thread. This way, the application starts all requests quickly and has to wait only until the last response is received, instead of having to wait for a response to each request before the next request can start. One example of such usage is an RSS or Atom feed aggregator.
- A page that sends many mail messages runs the code that sends the mail messages in a separate thread and doesn't wait for it to complete to continue processing. The thread that sends the mail messages continues processing after the page-level processing is completed and the application starts processing another page.
- An application does maintenance of user data, such as using update queries, deleting records, and so on, whenever a user logs into the site. If the application does the maintenance in a separate thread, the user gets an immediate response after logging in, without having to wait for the updates to complete.
When ColdFusion processes a page, the page executes in a single thread, called the page thread. The cfthread tag lets you create additional threads that can process independently of the page thread, and lets you synchronize thread processing, for example, by having the page thread wait until threads that you create complete their processing.