Develop work objects to run code in parallel
Before you begin
Your administrator must have configured at least one work manager using the administrative console.
Overview
To run code in parallel, or in a different J2EE context, wrap the code in a work object.
Procedure
- Create a work object.
A work object implements the com.ibm.websphere.asynchbeans.Work interface. For example
class SampleWork implements Work- Determine the number of work managers needed by this application component.
- Look up the work manager or managers using the work manager resource reference (or logical name) in the java:comp namespace. (For more information on resource references, see the topic References.)
The resource reference for the work manager (in this case, wm/myWorkManager) must be declared as a resource reference in the application deployment descriptor.InitialContext ic = new InitialContext(); WorkManager wm = (WorkManager)ic.lookup("java:comp/env/wm/myWorkManager");- Call the WorkManager.startWork() method using the work object as a parameter. For example
The startWork() method can take a startTimeout parameter. This specifies a hard time limit for the Work object to be started. The startWork() method returns a work item object. This object is a handle that provides a link from the component to the now running work object.Work w = new MyWork(...); WorkItem wi = wm.startWork(w);- [Optional] If your application component needs to wait for one or more of its running work objects to complete, call the WorkManager.join() method. For example
This method takes an array list of work items which your component wants to wait on and a flag that indicates whether the component will wait for one or all of the work objects to complete. You also can specify a timeout value.WorkItem wiA = wm.start(workA); WorkItem wiB = wm.start(workB); ArrayList l = new ArrayList(); l.add(wiA); l.add(wiB); if(wm.join(l, wm.JOIN_AND, 5000)) // block for up to 5 seconds { // both wiA and wiB finished } else { // timeout // we can check wiA.getStatus or wiB.getStatus to see which, if any, finished. }- Use the release() method to signal the unit of work to stop running. The unit of work then attempts to stop running as soon as possible. Typically, this action is completed by toggling a flag using a thread-safe approach like the following example
The Work.run() method can periodically examine this variable to check whether the loop exits or not.public synchronized void release() { released = true; }
See also
Work objects
Example: Work object
See Also
References