SlideShare a Scribd company logo
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

More Related Content

What's hot

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
maksym220889
 
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
Antonio 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 typescript
Katy Slemon
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPL
Gyuwon Yi
 
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
Antonio Goncalves
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
Ruben Inoto Soto
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj 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 CompletableFutures
Haim 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 question
Antonio Goncalves
 
Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
Anders Göransson
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
Jussi Pohjolainen
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
VNG
 
Completable future
Completable futureCompletable future
Completable future
Srinivasan Raghvan
 
Scalamen and OT
Scalamen and OTScalamen and OT
Scalamen and OT
getch123
 
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
Roberto Cortez
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
Jari Abbas
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
Java components in mule
Java components in muleJava components in mule
Java components in mule
Harish43
 
Spring boot
Spring bootSpring 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
Nina Zakharenko
 

What's hot (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
 

Similar to Concurrency and Thread-Safe Data Processing in Background Tasks

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha 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 NL
Arie Leeuwesteijn
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Leonid Maslov
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
Minh Tran
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
Mark Trostler
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
Srikanth 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 Quasar
Gal 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 Functions
Massimo 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 Android
Fernando 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 & Jetpack
Nelson Glauber Leal
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
KatyShimizu
 
[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
KatyShimizu
 
Play Framework
Play FrameworkPlay Framework
Play Framework
Harinath Krishnamoorthy
 
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 Scala
WO Community
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
Iulian 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 & Jetpack
Nelson Glauber Leal
 
Durable Functions
Durable FunctionsDurable Functions
Durable Functions
Matti Petrelius
 
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
Ahmed Assaf
 

Similar to 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
 

More from WO Community

KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
WO Community
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
WO 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 systems
WO Community
 
Build and deployment
Build and deploymentBuild and deployment
Build and deployment
WO Community
 
High availability
High availabilityHigh availability
High availability
WO Community
 
Reenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWSReenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWS
WO 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 World
WO Community
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
WO Community
 
Deploying WO on Windows
Deploying WO on WindowsDeploying WO on Windows
Deploying WO on Windows
WO Community
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
WO Community
 
Life outside WO
Life outside WOLife outside WO
Life outside WO
WO Community
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
WO Community
 
Advanced Apache Cayenne
Advanced Apache CayenneAdvanced Apache Cayenne
Advanced Apache Cayenne
WO Community
 
Migrating existing Projects to Wonder
Migrating existing Projects to WonderMigrating existing Projects to Wonder
Migrating existing Projects to Wonder
WO Community
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
WO Community
 
iOS for ERREST
iOS for ERRESTiOS for ERREST
iOS for ERREST
WO Community
 
"Framework Principal" pattern
"Framework Principal" pattern"Framework Principal" pattern
"Framework Principal" pattern
WO Community
 
Filtering data with D2W
Filtering data with D2W Filtering data with D2W
Filtering data with D2W
WO Community
 
WOver
WOverWOver
Localizing your apps for multibyte languages
Localizing your apps for multibyte languagesLocalizing your apps for multibyte languages
Localizing your apps for multibyte languages
WO Community
 

More from 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
 

Recently uploaded

Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
flufftailshop
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 

Recently uploaded (20)

Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 

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