You can run work objects in parallel, or in a different J2EE context,
by wrapping the code in a work object.
Before you begin
Your administrator must have configured at least one work manager
using the administrative console.
About this task
To run code in parallel, 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, refer to the References topic.)
InitialContext ic = new InitialContext();
WorkManager wm = (WorkManager)ic.lookup("java:comp/env/wm/myWorkManager");
The resource reference for the work manager (in this case, wm/myWorkManager)
must be declared as a resource reference in the application deployment descriptor.
- Call the WorkManager.startWork() method using the work object as
a parameter. For example:
Work w = new MyWork(...);
WorkItem wi = wm.startWork(w);
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.
- [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:
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.
}
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.
- 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:
public synchronized void release()
{
released = true;
}
The Work.run() method can periodically examine this variable to check
whether the loop exits or not.