ColdBox HMVC Documentation
DocsSourceSupportTraining
6.x
6.x
  • Introduction
  • Intro
    • Release History
      • What's New With 6.11.0
      • What's New With 6.10.0
      • What's New With 6.9.0
      • What's New With 6.8.2
      • What's New With 6.8.1
      • What's New With 6.8.0
      • What's New With 6.7.0
      • What's New With 6.6.1
      • What's New With 6.6.0
      • What's New With 6.5.x
      • What's New With 6.4.0
      • What's New With 6.3.0
      • What's New With 6.2.x
      • What's New With 6.1.0
      • What's New With 6.0.0
      • Upgrading to ColdBox 6
    • About This Book
    • Author
  • For Newbies
    • 60 Minute Quick Start
      • Installing ColdBox
      • My First ColdBox Application
      • My First Handler & View
      • Linking Events Together
      • Working With Event Handlers
      • Adding A Layout
      • Adding A Model
      • RESTFul Data
      • Next Steps
  • Getting Started
    • Getting Started Guide
    • Installation
    • Conventions
    • Configuration
      • ColdBox.cfc
        • Configuration Directives
          • CacheBox
          • ColdBox
          • Conventions
          • Environments
          • Flash
          • InterceptorSettings
          • Interceptors
          • Layouts
          • LayoutSettings
          • LogBox
          • Modules
          • ModuleSettings
          • Settings
          • WireBox
        • System Settings (Java Properties and Environment Variables)
      • Using Settings
      • Bootstrapper - Application.cfc
  • The Basics
    • Request Context
    • Routing
      • Requirements
        • Rewrite Rules
      • Application Router
      • Routing DSL
        • Routing By Convention
        • Pattern Placeholders
        • Routing Methods
        • Resourceful Routes
        • Named Routes
        • Routing Groups
        • Routing Namespaces
      • Building Routable Links
      • RESTFul Extension Detection
      • HTTP Method Spoofing
      • HTML Base Tag
      • Pathinfo Providers
    • Event Handlers
      • How are events called?
      • Getting & Setting Values
      • Setting Views
      • Relocating
      • Rendering Data
      • Sending Files
      • Interception Methods
        • Pre Advices
        • Post Advices
        • Around Advices
      • Model Integration
        • Model Data Binding
      • HTTP Method Security
      • Implicit Methods
      • Executing Events
      • Executing Routes
      • Viewlets - Reusable Events
      • Event Caching
      • Validation
    • Layouts & Views
      • Views
        • Rendering Views
        • Rendering External Views
        • Rendering With Local Variables
        • Rendering Collections
        • View Caching
        • View Helpers
        • View Events
      • Layouts
        • Basic Layouts
        • Default Layout
        • Nested Layouts
        • Overriding Layouts
        • Layouts From A Module
        • Layout Helpers
        • Layout Events
      • Implicit Layout-View Declarations
      • Helpers UDF's
      • ColdBox Elixir
    • Models
      • Domain Modeling
        • Service Layer
        • Data Layers
        • Book
      • Conventions Location
      • WireBox Binder
      • Super Type Usage Methods
      • Injection DSL
        • ColdBox Namespace
        • CacheBox Namespace
        • EntityService Namespace
        • Executor Namespace
        • Java Namespace
        • LogBox Namespace
        • Models Namespace
        • Provider Namespace
        • WireBox Namespace
      • Object Scopes
      • Coding: Solo Style
        • Datasource
        • Contact.cfc
        • ContactDAO.cfc
        • ContactService.cfc
        • Contacts Handler
      • Coding: ActiveEntity Style
        • ORM
        • Contact.cfc
        • Contacts Handler
        • Views
      • Coding: Virtual Service Layer
        • ORM
        • Contacts.cfc
        • Contacts Handler
        • Views
      • Coding: ORM Scaffolding
        • ORM
        • Contacts.cfc
        • Scaffold
    • Interceptors
      • How do they work?
        • Conventions
      • Interceptor Declaration
      • Interceptor Registration
      • Dynamic Registration
      • Core Interception Points
        • Application Life Cycle Events
        • Object Creating Events
        • Layout-View Events
        • Module Events
        • CacheBox Events
      • Restricting Execution
      • Interceptor Output Buffer
      • Custom Events
        • Configuration Registration
        • Programmatic Registration
        • Listening
        • Announcing Interceptions
      • Unregistering Interceptors
      • Reporting Methods
      • Interceptor Asynchronicity
        • Async Announcements
        • Async Listeners With Join
        • Async Listeners No Join
        • Asynchronous Annotations
  • HMVC
    • Modules
      • Core Modules
      • Locations
      • Parent Configuration
      • Module Layout
        • Changing The Module Layout
      • Module Service
        • Module Lifecycle
        • Module Registration
        • Module Activation
        • Module Unloading
        • Common Methods
        • Loading New Modules
        • Loading A-la-carte Modules
        • Module Events
      • ModuleConfig
        • Public Module Properties
        • The Decorated Variables
        • The configure() Method
        • Module Settings
        • Environment Control
        • Interceptor Events
      • Module Event Executions
      • URL Routing
        • Default Route Execution
        • Module Routes Files
      • Module Async Scheduling
      • Request Context Module Methods
      • Layout and View Renderings
        • Layout/View Discovery
        • Overriding Views
        • Overriding Layouts
        • Default Module Layout
        • Explicit Module Renderings
      • Models
      • Module CF Mappings
      • Module Dependencies
      • Module Helpers
      • Module Bundles
      • Module Inception
  • Testing
    • Testing Quick Start
    • Testing ColdBox Applications
      • Test Harness
      • ColdBox Testing Classes
      • Common Testing Methods
      • Integration Testing
        • Life-Cycle Events
        • Request Setup()
        • The execute() Method
        • HTTP Testing Methods
        • Testing Without Virtual Application
        • Test Annotations
      • Interceptor Testing
      • Model Object Testing
      • Tips & Tricks
  • Digging Deeper
    • Async Programming
      • Async Pipelines & Futures
      • Parallel Computations
      • Executors
      • Scheduled Tasks
    • ColdBox Proxy
      • Getting Started
      • The Base Proxy Object
      • The Event Handlers
        • Distinguishing Request Types
        • RenderData()
      • Proxy Events
      • Standard Return Types
      • Caveats & Gotchas
    • Controller Decorator
    • Flash RAM
      • Flash Storage
      • Using Flash RAM
      • Creating Your Own Flash Scope
    • HTML Helper
    • REST Handler
    • Request Context Decorator
    • Recipes
      • Building REST APIs
      • Application Templates
      • ColdBox Exception Handling
      • Debugging ColdBox Apps
      • Clearing the View Cache
      • Basic HTTP Authentication Interceptor
    • Scheduled Tasks
  • Architecture Concepts
    • What is MVC
    • What is ColdBox
    • How ColdBox Works
    • Testing Concepts
      • Functional Testing
      • Non-Functional Testing
      • Bugs Cost Money
      • Static Testing
      • Dynamic Testing
      • Developer Focus
      • Testing Vocabulary
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
Export as PDF
  1. Digging Deeper
  2. Async Programming

Parallel Computations

Last updated 5 years ago

Was this helpful?

Here are some of the methods that will allow you to do parallel computations. Please note that the asyncManager() has shortcuts to these methods, but we always recommend using them via a new future, because then you can have further constructor options like: custom executor, debugging, loading CFML context and much more.

  • all( a1, a2, ... ):Future : This method accepts an infinite amount of future objects, closures or an array of closures/futures in order to execute them in parallel. It will return a future that when you call get() on it, it will retrieve an array of the results of all the operations.

  • allApply( items, fn, executor ):array : This function can accept an array of items or a struct of items of any type and apply a function to each of the item's in parallel. The fn argument receives the appropriate item and must return a result. Consider this a parallel map() operation.

  • anyOf( a1, a2, ... ):Future : This method accepts an infinite amount of future objects, closures or an array of closures/futures and will execute them in parallel. However, instead of returning all of the results in an array like all(), this method will return the future that executes the fastest! Race Baby!

  • withTimeout( timeout, timeUnit ) : Apply a timeout to all() or allApply() operations. The timeUnit can be: days, hours, microseconds, milliseconds, minutes, nanoseconds, and seconds. The default is milliseconds.

Please note that some of the methods above will return a ColdBox Future object that is backed by Java's CompletableFuture ()

Here are the method signatures for the methods above, which you can call from the asyncManager or a newly created future.

/**
 * This method accepts an infinite amount of future objects, closures or an array of future objects/closures
 * in order to execute them in parallel.  It will return back to you a future that will return back an array
 * of results from every future that was executed. This way you can further attach processing and pipelining
 * on the constructed array of values.
 *
 * <pre>
 * results = all( f1, f2, f3 ).get()
 * all( f1, f2, f3 ).then( (values) => logResults( values ) );
 * </pre>
 *
 * @result A future that will return the results in an array
 */
Future function all(){

/**
 * This function can accept an array of items or a struct and apply a function
 * to each of the item's in parallel.  The `fn` argument receives the appropriate item
 * and must return a result.  Consider this a parallel map() operation
 *
 * <pre>
 * // Array
 * allApply( items, ( item ) => item.getMemento() )
 * // Struct: The result object is a struct of `key` and `value`
 * allApply( data, ( item ) => item.key & item.value.toString() )
 * </pre>
 *
 * @items An array to process
 * @fn The function that will be applied to each of the array's items
 * @executor The custom executor to use if passed, else the forkJoin Pool
 *
 * @return An array with the items processed
 */
any function allApply( any items, required fn, executor ){

/**
 * This method accepts an infinite amount of future objects or closures and will execute them in parallel.
 * However, instead of returning all of the results in an array like all(), this method will return
 * the future that executes the fastest!
 *
 * <pre>
 * // Let's say f2 executes the fastest!
 * f2 = anyOf( f1, f2, f3 )
 * </pre>
 *
 * @return The fastest executed future
 */
Future function anyOf()

/**
 * This method seeds a timeout into this future that can be used by the following operations:
 *
 * - all()
 * - allApply()
 *
 * @timeout The timeout value to use, defaults to forever
 * @timeUnit The time unit to use, available units are: days, hours, microseconds, milliseconds, minutes, nanoseconds, and seconds. The default is milliseconds
 *
 * @returns This future
 */
Future function withTimeout( numeric timeout = 0, string timeUnit = "milliseconds" )

Here are some examples:

// Let's find the fastest dns server
var f = asyncManager().anyOf( ()=>dns1.resolve(), ()=>dns2.resolve() );

// Let's process some data
var data = [1,2, ... 100 ];
var results = asyncManager().all( data );

// Process multiple futures
var f1 = asyncManager.newFuture( function(){
    return "hello";
} );
var f2 = asyncManager.newFuture( function(){
    return "world!";
} );
var aResults = asyncManager.newFuture()
    .withTimeout( 5 )
    .all( f1, f2 );

// Process mementos for an array of objects
function index( event, rc, prc ){
    return async().allApply(
        orderService.findAll(),
        ( order ) => order.getMemento()
    );
}

Custom Executors

Please also note that you can choose your own Executor for the parallel computations by passing the executor via the newFuture() method.

var data = [ 1 ... 5000 ];
var results = newFuture( executor : asyncManager.$executors.newCachedThreadPool() )
    .all( data );

// Process mementos for an array of objects on a custom pool
function index( event, rc, prc ){
    return async().allApply(
        orderService.findAll(),
        ( order ) => order.getMemento(),
        async().$executors.newFixedThreadPool( 50 )
    );
}
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html