Asynchronous beans are a feature of IBM® WebSphere® Application Server V6.0. WebSphere Application Server includes a set of APIs that allow Java™ 2 Platform, Enterprise Edition (J2EE) applications to execute their tasks in parallel. An asynchronous bean is a Java object or Enterprise JavaBeans (EJB) component that can be executed asynchronously by a J2EE application. The bean runs asynchronously using the J2EE context of its creator. The types of asynchronous beans include the following:
- Work is an object that implements the
com.ibm.websphere.asynchbeans.Workinterface. This is run in parallel with its caller using theWorkManager.startWorkmethod. - AlarmListener is an object that implements the
com.ibm.websphere.asynchbeans.AlarmListenerinterface. This is called when a high-speed transient alarm expires. - EventListener is an object that can implement any interface. This is a lightweight asynchronous notification mechanism for asynchronous events within a single Java virtual machine (JVM). Its main use is envisioned to be J2EE components within a single EAR file signaling each other various application asynchronous events.
You can learn more about asynchronous beans in the Asynchronous beans programming guide and other resources available in the Resources section at the end of this article.
The next section covers how asynchronous beans can be used in Web services.
Use asynchronous beans in Web services
Note: For information on how to write Java Web services, refer to "WebSphere Version 6 Web Services Handbook Development and Deployment," one of many IBM Redbooks.
Consider a Web
service that fetches data from two different resources to perform its business
logic. You can use the Work object (one flavor of asynchronous beans) here to wrap
these two tasks (retrieving the data from resources). Now you can execute these
two tasks in parallel. For demonstration, consider this Web service that appends
the contents of two text files and returns them. The code samples shown
in Listings 1 and 2 illustrate how the Java bean is used to create this Web service.
Listing 1. Java bean used to create Web service
package com.demo.asynbean.ws;
import java.util.ArrayList;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.ibm.websphere.asynchbeans.WorkException;
import com.ibm.websphere.asynchbeans.WorkItem;
import com.ibm.websphere.asynchbeans.WorkManager;
/**
* Created on Jul 9, 2007
*
* @author Shailesh K Mishra (shailekm@in.ibm.com)
*
*/
public class WSAsyncBean {
WorkManager workManager = null;
/**
*
*/
public WSAsyncBean() {
super();
// TODO Auto-generated constructor stub
}
public String getContent() {
String str = "";
//get the WorkManager instance first.
if (workManager == null)
getWorkManager();
try {
WorkItem item = workManager.startWork(new FetchFileContentTask("1.txt"));
WorkItem item1 = workManager.startWork(new FetchFileContentTask("2.txt"));
//Create an ArrayList
ArrayList items = new ArrayList();
//Add the previous WorkItems to ArrayList
items.add(item);
items.add(item1);
//Join them using WorkManager workManager
workManager.join(items, WorkManager.JOIN_AND,(int) WorkManager.INDEFINITE);
FetchFileContentTask task1 = (FetchFileContentTask) item.getResult();
FetchFileContentTask task2 = (FetchFileContentTask) item1.getResult();
String contentFromFile1 = task1.getContent();
String contentFromFile2 = task2.getContent();
str = contentFromFile1 + contentFromFile2;
} catch (WorkException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
/**
*
*/
private void getWorkManager() {
try {
InitialContext ic = new InitialContext();
workManager = (WorkManager) ic.lookup("java:comp/env/wm/myWorkManager");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Listing 2. Java class implementing Work interface
package com.demo.asynbean.ws;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import com.ibm.websphere.asynchbeans.Work;
/**
* Created on Jul 7, 2007
* @author Shailesh K Mishra (shailekm@in.ibm.com)
*
*/
public class FetchFileContentTask implements Work {
String fileName = "";
String content ="";
public FetchFileContentTask(String filename) {
super();
this.fileName = filename;
}
/*
* (non-Javadoc)
* @see javax.resource.spi.work.Work#release()
*/
public void release() {}
/*
* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
StringBuffer buffer = new StringBuffer();
// read the text file present in root directory.
try {
/*
* read the given file name in this application's root dir(for demo).
* You can perform any task here, e.g.
* fetching data from DB, invoking some other app, web service, etc.
*/
URL url = new URL("http://localhost:9080/WSAsynBeans/"+fileName);
InputStream in = url.openConnection().getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line=br.readLine();
while (line != null) {
try {
buffer.append(line);
line=br.readLine();
}catch (IOException ioe) {
ioe.printStackTrace();
break;
}
}
content = new String(buffer);
} catch (NamingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return Returns the name.
*/
public String getContent() {
return content;
}
}
|
In Listing 1, the bean class obtains the reference of default
WorkManager by calling the getWorkManager method. Then it starts the
tasks of fetching the content from two source files (wrapped in the
FetchFileContentTask class) by calling the startWork method of
WorkManager. The FetchFileContentTask class implements the Work
interface, which provides two methods—run and release—to be
implemented. Listing 2 shows the code for the FetchFileContentTask
class. After both tasks are executed successfully in parallel, you retrieve the
file content from these tasks and append them. Finally, the appended string is
returned by the Web service.
In this article, you learned how to use asynchronous beans in Web services to improve performance. The advantage of using asynchronous beans is that they let a Web service execute its tasks simultaneously as parallel threads, while the threads are running in the same context as their creator.
Learn
- Get more information in the Asynchronous beans programming guide.
- Read "The wise work manager for
context-based scoping."
- Read "Develop high performance J2EE threads with WebSphere Application Server" (developerWorks, June
2006).
- IBM Redbooks: WebSphere Version 6 Web Services Handbook Development and Deployment
- The SOA and Web services zone on IBM developerWorks hosts hundreds of informative articles and introductory, intermediate, and advanced tutorials on how to develop Web services
applications.
- The IBM SOA Web site offers an overview of SOA and how IBM can help you get there.
- Stay current with developerWorks technical events and webcasts. Check out the following SOA and Web services tech briefings in particular:
- Get started on SOA with WebSphere's proven, flexible entry points
- Building SOA solutions and managing the service lifecycle
- SCA/SDO: To drive the next generation of SOA
- SOA reuse and connectivity
- Browse for books on these and other technical topics at the
Safari bookstore.
- Check out a quick Web services on demand demo.
- Get an RSS feed for this series. (Find out more about RSS.)
Get products and technologies
- Innovate your next development project with
IBM trial software, available for download or on DVD.
Discuss
- Participate in the discussion forum.
- Get involved in the developerWorks community by participating in developerWorks blogs.
Comments (Undergoing maintenance)






