Asynchronous programming

In ColdFusion, there is support for asynchronous programming via Future. A Future is an eventual result of an asynchronous operation.

Asynchronous programming is useful when you want to reduce the average response time of an application. You can use asynchronous programming to offload IO or database intensive tasks. Also, use asynchronous programming to improve the responsiveness of a UI.

Some of the benefits of asynchronous programming are:

  • Near real-time processing
  • Easy to distribute tasks
  • Uses its own worker threads
  • Dynamically configurable thread pool (Admin Console)
  • On-demand thread pool creation

For asynchronous programming, you can use the runAsync function.

Example

When salary is credited to our bank accounts, we pay various bills like credit cards, mortgage, utilities, and so on. The payments are dependent on salary or in this context, chained to salary.

<cfscript>

 getAccountBalance = function(){
            var balance = 120000;
            return balance;
 }

 function payCreditCardBill(accountBalance){
            var ccBill = 1890;
            return accountBalance-ccBill;
 }

 payEMIs = function(accountBalance){
            var mortgageEMI = 1000;
            var carLeaseEMI = 750;
            var healthInsuranceEMI = 250;

            return accountBalance-(mortgageEMI+carLeaseEMI+healthInsuranceEMI);
 }

 miscellenousExpenses = function(accountBalance){
            var shopping = 1500;
            var clubExpense  =1000;
            var casinoExpense = 2000;
            return accountBalance-(shopping+clubExpense+casinoExpense);
 }

 checkBalance = function(accountBalance){
            while(accountBalance > 5000){
                        accountBalance = miscellenousExpenses(accountBalance);
                                    }
            if(accountBalance < 5000)
                        throw (message="Account balance below threshold!!!", type="info");
 }

 errorHandler = function(error){
            if(error.message contains "Account balance below threshold!"){
                        return "You have reached your spending limit!";
            }
 }

 future = runAsync(getAccountBalance).then(payCreditCardBill).then(payEMIs).
 then(miscellenousExpenses).then(checkBalance).error(errorHandler);

 writelog(future.get());

</cfscript>

You can also use closures with the runAsync function.

For example,

<cfscript>
            future = runAsync(function(){return "I am invoked from RunAsync directly!";});
</cfscript>

Methods available with runAsync are:

  • cancel();
  • error(callback, timeout);
  • error(callback);
  • get();
  • get(timeout
  • isCancelled();
  • isDone();
  • then(callback);
  • then(callback, timeout);

Empty Future

An empty future is an object, which can be explicitly marked as complete with a result value. It can be used in producer/consumer scenarios.

For example,

<cfscript>
 p = runAsync(); // empty future
 p.complete(10); 
 writelog(p.get()); // displays 10
</cfscript>

The methods available on an empty Future are:

  • cancel()
  • get()
  • isCancelled()
  • isDone()
  • complete(value)

Executor Pool Configuration

In the Server Settings section in the Administrator, there is an option Executor Pool Configuration, which enables you to specify values for:

  • Core pool size: Core pool size is the minimum number of worker threads to keep alive. The value should be less than the value specified in Maximum Pool Size. The default value is 25.
  • Maximum pool size: Maximum number of threads that can ever be available in the pool. The default value is 50.
  • Keep alive time: Timeout in milliseconds for idle threads waiting for work. Threads use this timeout when there are more than the corePoolSize present in the pool. The default value is 2000 ms.
Executor Pool Configuration
Executor Pool Configuration

These settings enable you to finetune your async executor according to your requirements. Also, these property changes take effect without any server restart.

We have also added the following Admin APIs to support the properties mentioned above. These APIs are a part of runtime.cfc.

In the 2018 release of ColdFusion, to support the pool configuration settings, we have also added three new properties to the API, getRuntimeProperty(required propertyName). They are:

  • corePoolSize
  • maxPoolSize
  • keepAliveTime

For example,

<cfscript>
    // Login is always required.
    adminObj = createObject("component","cfide.adminapi.administrator");
    adminObj.login("admin");
    runtimeObj=createObject("component","cfide.adminapi.runtime");
    corePool=runtimeObj.getRuntimeProperty("corePoolSize");
    writeOutput("core pool size is: " & corePool & "<br/>");
    maxPool=runtimeObj.getRuntimeProperty("maxPoolSize");
    writeOutput("max pool size is: " & maxPool & "<br/>");
    keepAlive=runtimeObj.getruntimeProperty("keepAliveTime");
    writeOutput("keep alive time is: " & keepAlive & "<br/>");
</cfscript> 

Get help faster and easier

New user?