SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
MONTREAL 1/3 JULY 2011




Concurrency and Thread-Safe Data
Processing in Background Tasks
Kieran Kelleher
Green Island Consulting LLC
SmartleadsUSA LLC
SmartMix Technologies LLC
Why Background Threads?
•   “Background” = Not in the Request-Response thread (WOWorkerThread)

    •   We can execute long-running logic asynchronously in a background thread.

•   An action MAY be always or sometimes too long

    •   Examples

        •   importing a mailing list of 50 records versus a list of 100,000 records.

        •   Generating a report off a selection of 50 EOs versus 100,000 EOs.

        •   your app interacting with remote web services (connection timeouts, etc.)

        •   interacting with a merchant payment gateway (Credit Card processing)

        •   Administration & Bulk Data Processing Operations
Objectives
•   How to run simple background tasks with the least effort on your behalf.

•   Start an asynchronous task

•   Use a long response page to start a task, monitor and handle a task result

    •   with basic user feedback (busy)

    •   with better user feedback (progress, status)

•   How to work with EOF in the context of background threads.

•   How to pass arguments and return results (including EOs) from asynchronous tasks.

•   How to run a multi-threaded bulk data processing asynchronous task to get more done faster.

•   Introduce convenient classes in Wonder that are related to running tasks in background threads.
Anatomy of a “Task”
public class SimpleRunnable implements Runnable {

	    public void run() {

	    	    //Do a whole lot of stuff here

	    }
}




public class SimpleCallable implements Callable<ResultType> {
	
	    public ResultType call() {

	    	    //Do a whole lot of stuff here

           return _someResult;
	    }
}
Executing a Task
•   Use java.util.concurrent.*

    •   Convenient, easy to use.

•   In summary: Basic concurrency classes to understand

    •   Runnable, Callable, ExecutorService, Future

•   java.util.concurrent.ExecutorService interface

    •   executorService.execute( task );

    •   Future future = executorService.submit( task );

•   java.util.concurrent.Future interface

    •   future.get() or future.get(timeout, timeUnit)

    •   future.isDone()
Executing a Task
// Creating an ExecutorService in plain Java
ExecutorService executorService = Executors.newCachedThreadPool();

// Getting a reference to the WebObjects-friendly singleton ExecutorService
ExecutorService executorService = ERXExecutorService.executorService()

// Starting an asynchronous task (aka run it in another thread)
Runnable task = new MyRunnableTask();
executorService.execute( task );

// Starting an asynchronous task and keeping an eye on it
Future future = executorService.submit( task );




// Starting a task in a WebObjects action
public WOActionResults dispatchBackgroundTask() {
	   MyTask task = new MyTask();
	   ERXExecutorService.executorService().execute(task);
	   return null;
}
Demo 1
ERXExecutorService
                               creates a             ERXTaskThreadPoolExecutor              returns         ERXFutureTask
ERXExecutorService                                       extends ThreadPoolExecutor
                                                                                                            implements Future
                                                         implements ExecutorService

    (utility class)
                                                            has a
                                                                               ERXThreadFactory
                                                                              implements ThreadFactory

•   Usage
                                                                              creates
    •   ExecutorService es = ERXExecutorService.executorService();
                                                                                                  ERXTaskThread
    •   es.execute( runnable );                                                                     extends Thread

    •   Future future = es.submit( task );

    •   You generally don’t need to directly use the stuff to the right :-)
Benefits of using ExecutorService instances
              returned by ERXExecutorService

•   Allows for loosely coupled plain Runnable and Callable tasks.

    •   No subclassing necessary to get WO integration!

•   EC Safety Net: Automatically unlocks all EC’s at the end of task execution (no subclassing needed)

    •   NOT a reason to ignore locking!

•   TODO: ERXThreadStorage “safe” cloning.

•   By the way...

    •   ERXTaskThread subclass of Thread used

    •   supports use of ERXExecutionStateTransition interface in your task.
The “Ideal” Long Response Page?

•   Provides feedback to the user

•   Simple UI and easy to understand user experience

•   Can be reusable and easy (even pleasant) to implement

    •   ! WOLongResponsePage

•   Controls the user by making them wait

    •   May not be a good idea for very long tasks
Demo 2
CCAjaxLongResponsePage

• Resides in ERCoolComponents framework
• Easy to use ... really!
• CSS styleable
• Customizable via Properties
CCAjaxLongResponsePage
// Basic usage: run a task in long response page and return to the same page

	    public WOActionResults dispatchBackgroundTaskInLongResponsePage() {
	    	    Runnable task = new MyRunnableTask();
	    	
	    	    CCAjaxLongResponsePage nextPage = pageWithName(CCAjaxLongResponsePage.class);
	    	    nextPage.setTask(task);
	    	
	    	    return nextPage;
	    }

#####################################################################
# Optional configuration properties
#####################################################################

# A default status message to display if the long running task does not implement ERXStatusInterface
er.coolcomponents.CCAjaxLongResponsePage.defaultStatus=Please wait...

# Stylesheet for CCAjaxLongResponsePage
er.coolcomponents.CCAjaxLongResponsePage.stylesheet.framework = ERCoolComponents
er.coolcomponents.CCAjaxLongResponsePage.stylesheet.filename = CCAjaxLongResponsePage.css

# Useful for developing a custom CSS style-sheet. When set to true, this flag prevents AJAX refresh on all containers
# on the CCAjaxLongResponsePage and keeps the page open indefinitely even after the task has completed.
er.coolcomponents.CCAjaxLongResponsePage.stayOnLongResponsePageIndefinitely = false

# Default refresh interval for CCAjaxLongResponsePage
#er.coolcomponents.CCAjaxLongResponsePage.refreshInterval = 2

#Defines a default controller class, other than the hard-coded default, for handling task errors for the application
er.coolcomponents.CCAjaxLongResponsePage.nextPageForErrorResultControllerClassName=com.myproject.MyErrorController
Monitoring & Controlling Tasks
•   ERXStatusInterface

    •   public String status();

•   ERXTaskPercentComplete

    •   public Double percentComplete();

•   IERXStoppable

    •   public void stop();

•   Only ONE method in each interface!! :-)
Demo 3
EOF Background Tasks
•   Good Practices

    •   Only pass EOGlobalIDs (or raw rows) between threads

    •   Manual lock/unlock. --- EC lock() / try / finally / unlock()

    •   Avoid using default EOObjectStoreCoordinator

•   Things to remember

    •   Task constructor code does not run in the task thread.

        •   Pass in an EO in constructor - convert to EOGlobalID
FYI, About the Demo EOModel
                (Number Crunching for the sake of it)


                                                  ResultItem
                                                   ResultItem
     TaskInfo                                       ResultItem
                                                     ResultItem
       Entity                                         ResultItem
                                                       ResultItem
                                                          Entity




Represents a single               Represents result of one loop iteration.
execution of a task               1) Checking if a number if Prime
                                  2) Checking if a Prime is a Factorial Prime
Demo 4
How It Works

      Originating Page                                   CCAjaxLongResponsePage




            Callable              nextPage.setTask(..)            Callable




IERXPerformWOActionForResult
         nextPage.setNextPageForResultController(..)     IERXPerformWOActionForResult   Result Page
IERXPerformWOActionForResult
•   Interface

    •   public WOActionResults performAction();

    •   public void setResult(Object result);

•   Utility Implementation

    •   ERXNextPageForResultWOAction

    •   new ERXNextPageForResultWOAction(resultPage, "resultKey");
Customize end of task WOActionResults behavior

	   // Example of action in originating page to return a long response page

    public WOActionResults performTaskWithCustomResultController() {

	   	    // Create the controller for handling the result and returning the next page after the task is done
	   	    IERXPerformWOActionForResult controller = new ERXNextPageForResultWOAction(pageWithName(MyResultPage.class), "resultKeyInPage");
	   	
         // Create the task
	   	    Callable<EOGlobalID> task = new MyCallableTask();
	   	
	   	    // Create the CCAjaxLongResponsePage instance
	   	    CCAjaxLongResponsePage nextPage = pageWithName(CCAjaxLongResponsePage.class);

         // Push controller and the task into CCAjaxLongResponsePage
	   	    nextPage.setNextPageForResultController(controller);
	   	    nextPage.setTask(task);
	   	
         // Return the CCAjaxLongResponsePage instance
	   	    return nextPage;
	   }
Avoiding the default EOObjectStoreCoordinator
                                     in your task
// Using an OSC from a pool of OSC dedicated to background tasks. Pool size configurable.
EOObjectStoreCoordinator osc = ERXTaskObjectStoreCoordinatorPool.objectStoreCoordinator();

EOEditingContext ec = ERXEC.newEditingContext( osc );
ec.lock();
try {
    // Do stuff

} finally {
    ec.unlock();
}



# Configure the default OSC pool size for background tasks with property
er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = 4




// Convenience class ERXAbstractTask
// @see ERXAbstractTask#newEditingContext()

public class MyRunnable extends ERXAbstractTask




Just extend ERXAbstractTask and call newEditingContext() !
Handling the return object
// If you implement your own IERXPerformWOActionForResult and result is an EOGlobalID



if (_result instanceof EOGlobalID) {
	
	   // Create a new EC
	   EOEditingContext ec = ERXEC.newEditingContext();

	   // Let's ensure fresh ec since we are likely coming out of a background task
	   ec.setFetchTimestamp(System.currentTimeMillis());
	
	   _result = ec.faultForGlobalID((EOGlobalID) _result, ec);
	
}

_nextPage.takeValueForKey(_result, _nextPageResultKey);
Multi-threaded Tasks
                   Task (Manager)




         Fixed size private ExecutorService


Child
Child      Child
           Child                    Child
                                    Child     Child
                                              Child
Child      Child                    Child     Child
Demo 5
Multi-threaded task notes
•   Parent task can delegate batches of work to child tasks

    •   Concept - many child tasks serviced by finite thread count ExecutorService

•   Use EOGlobalIDs (or raw rows) as parameters to the child tasks.

    •   DO NOT pass EOs directly to child tasks.

•   Fixed thread pool

    •   static var: pool is shared between all instances of the task (resource conservative)

    •   instance var: pool is dedicated to each task (careful)

•   Take care to correctly size the ERXTaskObjectStoreCoordinatorPool

    •   er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = n

•   Use Futures to track child task completion. Don’t exit until all child tasks have completed.
Working with Fixed Thread Pool ExecutorService

ExecutorService es = ERXExecutorService.newFiniteThreadPool(4);

boolean isRejected = true;

while ( isRejected ) {

	    try {
	
	    	    Future<?> future = es.submit(childTask);
	    	
	    } catch (RejectedExecutionException e) {
	
	    	       try {
	    	
	    	       	    Thread.sleep(2000);
	    	       	
	    	       } catch (InterruptedException e1) {
	    	       	    // Handle that
	    	       }
	    }
}
Passing Parameters to a Task
    private final EOGlobalID _myObjectID

     // Example Task Constructor
	   public MyUpdateTask(MyEntityClass eo) {

	   	   if (eo.isNewObject()) {
	   	   	   throw new IllegalArgumentException("MyEntityClass cannot be a new unsaved object");
	   	   }
	   	
	   	   // Grab GID reference before the task is started.
	   	   _myObjectID = eo.editingContext().globalIDForObject(eo);

	   }
Problems and Solutions (1/2)
•   Memory when Processing Huge Data Sets

    •   Allocate More Memory

    •   Force garbage collection (for example if above a % usage)

    •   Recycle EOEditingContexts periodically (see demo T06xxx.java)

•   Large toMany Relationships

    •   Remove the toMany from the EOModel and use
        ERXUnmodeledToManyRelationship

        •   @see example usage in ‘BackgroundTasks’ demo:

            •   TaskInfo.resultItems relationship.
Problems and Solutions (2/2)
•   Prevent bottleneck in default EOObjectStoreCoordinator

    •   ERXTaskObjectStoreCoordinatorPool.objectStoreCoordinator()

    •   er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = n

    •   Implement IERXRefreshPage interface on result page to prevent stale EO result.

        •   in refresh() call ERXEOControlUtilities.refreshObject( eo );

        •   @see demo TaskInfoPage and logic in ERXNextPageForResultController

•   Use Fresh Data in your background tasks

    •   ec.setFetchTimestamp(System.currentTimeMillis());

    •   ERXEOControlUtilities.refreshObject( eo );
More Information
•   Demo App: wonder/Examples/Misc/BackgroundTasks

•   Java API Docs

    •   Runnable, Callable, ExecutorService, Future, Executors

•   Wonder classes and javadoc

    •   CCAjaxLongResponsePage

    •   IERXPerformWOActionForResult / ERXNextPageForResultWOAction, IERXRefreshPage

    •   ERXStatusInterface, ERXTaskPercentComplete, IERXStoppable

    •   ERXExecutorService

    •   ERXAbstractTask, ERXTaskObjectStoreCoordinatorPool

•   Effective Java, 2nd Edition by Joshua Bloch, chapter 10
MONTREAL 1/3 JULY 2011




Q&A
Concurrency and Thread-Safe Data Processing in Background Tasks

Kieran Kelleher

Contenu connexe

Tendances

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutesAntonio Goncalves
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPLGyuwon Yi
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesHaim Yadid
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionAntonio Goncalves
 
Javascript closures
Javascript closures Javascript closures
Javascript closures VNG
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OTgetch123
 
Java EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldJava EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldRoberto Cortez
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskHoang Ngo
 
Java components in mule
Java components in muleJava components in mule
Java components in muleHarish43
 
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoElegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoNina Zakharenko
 

Tendances (20)

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPL
 
What's new in Java EE 6
What's new in Java EE 6What's new in Java EE 6
What's new in Java EE 6
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the question
 
Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
 
Completable future
Completable futureCompletable future
Completable future
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OT
 
Java EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldJava EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real World
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
 
Java components in mule
Java components in muleJava components in mule
Java components in mule
 
Spring boot
Spring bootSpring boot
Spring boot
 
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoElegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
 

Similaire à Concurrency and Thread-Safe Data Processing in Background Tasks

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application ArchitectureMark Trostler
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarGal Marder
 
Workflow as code with Azure Durable Functions
Workflow as code with Azure Durable FunctionsWorkflow as code with Azure Durable Functions
Workflow as code with Azure Durable FunctionsMassimo Bonanni
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackNelson Glauber Leal
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade ServerlessKatyShimizu
 
Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)Hendrik Ebbers
 
Building Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaBuilding Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaWO Community
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_groupSkills Matter
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debuggerIulian Dragos
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackNelson Glauber Leal
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 

Similaire à Concurrency and Thread-Safe Data Processing in Background Tasks (20)

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
Workflow as code with Azure Durable Functions
Workflow as code with Azure Durable FunctionsWorkflow as code with Azure Durable Functions
Workflow as code with Azure Durable Functions
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)
 
Building Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with ScalaBuilding Concurrent WebObjects applications with Scala
Building Concurrent WebObjects applications with Scala
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Durable Functions
Durable FunctionsDurable Functions
Durable Functions
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 

Plus de WO Community

In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
Using Nagios to monitor your WO systems
Using Nagios to monitor your WO systemsUsing Nagios to monitor your WO systems
Using Nagios to monitor your WO systemsWO Community
 
Build and deployment
Build and deploymentBuild and deployment
Build and deploymentWO Community
 
Reenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWSReenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWSWO Community
 
Chaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real WorldChaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real WorldWO Community
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful ControllersWO Community
 
Deploying WO on Windows
Deploying WO on WindowsDeploying WO on Windows
Deploying WO on WindowsWO Community
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnitWO Community
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Advanced Apache Cayenne
Advanced Apache CayenneAdvanced Apache Cayenne
Advanced Apache CayenneWO Community
 
Migrating existing Projects to Wonder
Migrating existing Projects to WonderMigrating existing Projects to Wonder
Migrating existing Projects to WonderWO Community
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative versionWO Community
 
"Framework Principal" pattern
"Framework Principal" pattern"Framework Principal" pattern
"Framework Principal" patternWO Community
 
Filtering data with D2W
Filtering data with D2W Filtering data with D2W
Filtering data with D2W WO Community
 
Localizing your apps for multibyte languages
Localizing your apps for multibyte languagesLocalizing your apps for multibyte languages
Localizing your apps for multibyte languagesWO Community
 

Plus de WO Community (20)

KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Using Nagios to monitor your WO systems
Using Nagios to monitor your WO systemsUsing Nagios to monitor your WO systems
Using Nagios to monitor your WO systems
 
Build and deployment
Build and deploymentBuild and deployment
Build and deployment
 
High availability
High availabilityHigh availability
High availability
 
Reenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWSReenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWS
 
Chaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real WorldChaining the Beast - Testing Wonder Applications in the Real World
Chaining the Beast - Testing Wonder Applications in the Real World
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Deploying WO on Windows
Deploying WO on WindowsDeploying WO on Windows
Deploying WO on Windows
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
 
Life outside WO
Life outside WOLife outside WO
Life outside WO
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Advanced Apache Cayenne
Advanced Apache CayenneAdvanced Apache Cayenne
Advanced Apache Cayenne
 
Migrating existing Projects to Wonder
Migrating existing Projects to WonderMigrating existing Projects to Wonder
Migrating existing Projects to Wonder
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
 
iOS for ERREST
iOS for ERRESTiOS for ERREST
iOS for ERREST
 
"Framework Principal" pattern
"Framework Principal" pattern"Framework Principal" pattern
"Framework Principal" pattern
 
Filtering data with D2W
Filtering data with D2W Filtering data with D2W
Filtering data with D2W
 
WOver
WOverWOver
WOver
 
Localizing your apps for multibyte languages
Localizing your apps for multibyte languagesLocalizing your apps for multibyte languages
Localizing your apps for multibyte languages
 

Dernier

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Dernier (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Concurrency and Thread-Safe Data Processing in Background Tasks

  • 1. MONTREAL 1/3 JULY 2011 Concurrency and Thread-Safe Data Processing in Background Tasks Kieran Kelleher Green Island Consulting LLC SmartleadsUSA LLC SmartMix Technologies LLC
  • 2. Why Background Threads? • “Background” = Not in the Request-Response thread (WOWorkerThread) • We can execute long-running logic asynchronously in a background thread. • An action MAY be always or sometimes too long • Examples • importing a mailing list of 50 records versus a list of 100,000 records. • Generating a report off a selection of 50 EOs versus 100,000 EOs. • your app interacting with remote web services (connection timeouts, etc.) • interacting with a merchant payment gateway (Credit Card processing) • Administration & Bulk Data Processing Operations
  • 3. Objectives • How to run simple background tasks with the least effort on your behalf. • Start an asynchronous task • Use a long response page to start a task, monitor and handle a task result • with basic user feedback (busy) • with better user feedback (progress, status) • How to work with EOF in the context of background threads. • How to pass arguments and return results (including EOs) from asynchronous tasks. • How to run a multi-threaded bulk data processing asynchronous task to get more done faster. • Introduce convenient classes in Wonder that are related to running tasks in background threads.
  • 4. Anatomy of a “Task” public class SimpleRunnable implements Runnable { public void run() { //Do a whole lot of stuff here } } public class SimpleCallable implements Callable<ResultType> { public ResultType call() { //Do a whole lot of stuff here return _someResult; } }
  • 5. Executing a Task • Use java.util.concurrent.* • Convenient, easy to use. • In summary: Basic concurrency classes to understand • Runnable, Callable, ExecutorService, Future • java.util.concurrent.ExecutorService interface • executorService.execute( task ); • Future future = executorService.submit( task ); • java.util.concurrent.Future interface • future.get() or future.get(timeout, timeUnit) • future.isDone()
  • 6. Executing a Task // Creating an ExecutorService in plain Java ExecutorService executorService = Executors.newCachedThreadPool(); // Getting a reference to the WebObjects-friendly singleton ExecutorService ExecutorService executorService = ERXExecutorService.executorService() // Starting an asynchronous task (aka run it in another thread) Runnable task = new MyRunnableTask(); executorService.execute( task ); // Starting an asynchronous task and keeping an eye on it Future future = executorService.submit( task ); // Starting a task in a WebObjects action public WOActionResults dispatchBackgroundTask() { MyTask task = new MyTask(); ERXExecutorService.executorService().execute(task); return null; }
  • 8. ERXExecutorService creates a ERXTaskThreadPoolExecutor returns ERXFutureTask ERXExecutorService extends ThreadPoolExecutor implements Future implements ExecutorService (utility class) has a ERXThreadFactory implements ThreadFactory • Usage creates • ExecutorService es = ERXExecutorService.executorService(); ERXTaskThread • es.execute( runnable ); extends Thread • Future future = es.submit( task ); • You generally don’t need to directly use the stuff to the right :-)
  • 9. Benefits of using ExecutorService instances returned by ERXExecutorService • Allows for loosely coupled plain Runnable and Callable tasks. • No subclassing necessary to get WO integration! • EC Safety Net: Automatically unlocks all EC’s at the end of task execution (no subclassing needed) • NOT a reason to ignore locking! • TODO: ERXThreadStorage “safe” cloning. • By the way... • ERXTaskThread subclass of Thread used • supports use of ERXExecutionStateTransition interface in your task.
  • 10. The “Ideal” Long Response Page? • Provides feedback to the user • Simple UI and easy to understand user experience • Can be reusable and easy (even pleasant) to implement • ! WOLongResponsePage • Controls the user by making them wait • May not be a good idea for very long tasks
  • 12. CCAjaxLongResponsePage • Resides in ERCoolComponents framework • Easy to use ... really! • CSS styleable • Customizable via Properties
  • 13. CCAjaxLongResponsePage // Basic usage: run a task in long response page and return to the same page public WOActionResults dispatchBackgroundTaskInLongResponsePage() { Runnable task = new MyRunnableTask(); CCAjaxLongResponsePage nextPage = pageWithName(CCAjaxLongResponsePage.class); nextPage.setTask(task); return nextPage; } ##################################################################### # Optional configuration properties ##################################################################### # A default status message to display if the long running task does not implement ERXStatusInterface er.coolcomponents.CCAjaxLongResponsePage.defaultStatus=Please wait... # Stylesheet for CCAjaxLongResponsePage er.coolcomponents.CCAjaxLongResponsePage.stylesheet.framework = ERCoolComponents er.coolcomponents.CCAjaxLongResponsePage.stylesheet.filename = CCAjaxLongResponsePage.css # Useful for developing a custom CSS style-sheet. When set to true, this flag prevents AJAX refresh on all containers # on the CCAjaxLongResponsePage and keeps the page open indefinitely even after the task has completed. er.coolcomponents.CCAjaxLongResponsePage.stayOnLongResponsePageIndefinitely = false # Default refresh interval for CCAjaxLongResponsePage #er.coolcomponents.CCAjaxLongResponsePage.refreshInterval = 2 #Defines a default controller class, other than the hard-coded default, for handling task errors for the application er.coolcomponents.CCAjaxLongResponsePage.nextPageForErrorResultControllerClassName=com.myproject.MyErrorController
  • 14. Monitoring & Controlling Tasks • ERXStatusInterface • public String status(); • ERXTaskPercentComplete • public Double percentComplete(); • IERXStoppable • public void stop(); • Only ONE method in each interface!! :-)
  • 16. EOF Background Tasks • Good Practices • Only pass EOGlobalIDs (or raw rows) between threads • Manual lock/unlock. --- EC lock() / try / finally / unlock() • Avoid using default EOObjectStoreCoordinator • Things to remember • Task constructor code does not run in the task thread. • Pass in an EO in constructor - convert to EOGlobalID
  • 17. FYI, About the Demo EOModel (Number Crunching for the sake of it) ResultItem ResultItem TaskInfo ResultItem ResultItem Entity ResultItem ResultItem Entity Represents a single Represents result of one loop iteration. execution of a task 1) Checking if a number if Prime 2) Checking if a Prime is a Factorial Prime
  • 19. How It Works Originating Page CCAjaxLongResponsePage Callable nextPage.setTask(..) Callable IERXPerformWOActionForResult nextPage.setNextPageForResultController(..) IERXPerformWOActionForResult Result Page
  • 20. IERXPerformWOActionForResult • Interface • public WOActionResults performAction(); • public void setResult(Object result); • Utility Implementation • ERXNextPageForResultWOAction • new ERXNextPageForResultWOAction(resultPage, "resultKey");
  • 21. Customize end of task WOActionResults behavior // Example of action in originating page to return a long response page public WOActionResults performTaskWithCustomResultController() { // Create the controller for handling the result and returning the next page after the task is done IERXPerformWOActionForResult controller = new ERXNextPageForResultWOAction(pageWithName(MyResultPage.class), "resultKeyInPage"); // Create the task Callable<EOGlobalID> task = new MyCallableTask(); // Create the CCAjaxLongResponsePage instance CCAjaxLongResponsePage nextPage = pageWithName(CCAjaxLongResponsePage.class); // Push controller and the task into CCAjaxLongResponsePage nextPage.setNextPageForResultController(controller); nextPage.setTask(task); // Return the CCAjaxLongResponsePage instance return nextPage; }
  • 22. Avoiding the default EOObjectStoreCoordinator in your task // Using an OSC from a pool of OSC dedicated to background tasks. Pool size configurable. EOObjectStoreCoordinator osc = ERXTaskObjectStoreCoordinatorPool.objectStoreCoordinator(); EOEditingContext ec = ERXEC.newEditingContext( osc ); ec.lock(); try { // Do stuff } finally { ec.unlock(); } # Configure the default OSC pool size for background tasks with property er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = 4 // Convenience class ERXAbstractTask // @see ERXAbstractTask#newEditingContext() public class MyRunnable extends ERXAbstractTask Just extend ERXAbstractTask and call newEditingContext() !
  • 23. Handling the return object // If you implement your own IERXPerformWOActionForResult and result is an EOGlobalID if (_result instanceof EOGlobalID) { // Create a new EC EOEditingContext ec = ERXEC.newEditingContext(); // Let's ensure fresh ec since we are likely coming out of a background task ec.setFetchTimestamp(System.currentTimeMillis()); _result = ec.faultForGlobalID((EOGlobalID) _result, ec); } _nextPage.takeValueForKey(_result, _nextPageResultKey);
  • 24. Multi-threaded Tasks Task (Manager) Fixed size private ExecutorService Child Child Child Child Child Child Child Child Child Child Child Child
  • 26. Multi-threaded task notes • Parent task can delegate batches of work to child tasks • Concept - many child tasks serviced by finite thread count ExecutorService • Use EOGlobalIDs (or raw rows) as parameters to the child tasks. • DO NOT pass EOs directly to child tasks. • Fixed thread pool • static var: pool is shared between all instances of the task (resource conservative) • instance var: pool is dedicated to each task (careful) • Take care to correctly size the ERXTaskObjectStoreCoordinatorPool • er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = n • Use Futures to track child task completion. Don’t exit until all child tasks have completed.
  • 27. Working with Fixed Thread Pool ExecutorService ExecutorService es = ERXExecutorService.newFiniteThreadPool(4); boolean isRejected = true; while ( isRejected ) { try { Future<?> future = es.submit(childTask); } catch (RejectedExecutionException e) { try { Thread.sleep(2000); } catch (InterruptedException e1) { // Handle that } } }
  • 28. Passing Parameters to a Task private final EOGlobalID _myObjectID // Example Task Constructor public MyUpdateTask(MyEntityClass eo) { if (eo.isNewObject()) { throw new IllegalArgumentException("MyEntityClass cannot be a new unsaved object"); } // Grab GID reference before the task is started. _myObjectID = eo.editingContext().globalIDForObject(eo); }
  • 29. Problems and Solutions (1/2) • Memory when Processing Huge Data Sets • Allocate More Memory • Force garbage collection (for example if above a % usage) • Recycle EOEditingContexts periodically (see demo T06xxx.java) • Large toMany Relationships • Remove the toMany from the EOModel and use ERXUnmodeledToManyRelationship • @see example usage in ‘BackgroundTasks’ demo: • TaskInfo.resultItems relationship.
  • 30. Problems and Solutions (2/2) • Prevent bottleneck in default EOObjectStoreCoordinator • ERXTaskObjectStoreCoordinatorPool.objectStoreCoordinator() • er.extensions.concurrency.ERXTaskObjectStoreCoordinatorPool.maxCoordinators = n • Implement IERXRefreshPage interface on result page to prevent stale EO result. • in refresh() call ERXEOControlUtilities.refreshObject( eo ); • @see demo TaskInfoPage and logic in ERXNextPageForResultController • Use Fresh Data in your background tasks • ec.setFetchTimestamp(System.currentTimeMillis()); • ERXEOControlUtilities.refreshObject( eo );
  • 31. More Information • Demo App: wonder/Examples/Misc/BackgroundTasks • Java API Docs • Runnable, Callable, ExecutorService, Future, Executors • Wonder classes and javadoc • CCAjaxLongResponsePage • IERXPerformWOActionForResult / ERXNextPageForResultWOAction, IERXRefreshPage • ERXStatusInterface, ERXTaskPercentComplete, IERXStoppable • ERXExecutorService • ERXAbstractTask, ERXTaskObjectStoreCoordinatorPool • Effective Java, 2nd Edition by Joshua Bloch, chapter 10
  • 32. MONTREAL 1/3 JULY 2011 Q&A Concurrency and Thread-Safe Data Processing in Background Tasks Kieran Kelleher