Skip to main content

Web services tip: Use asynchronous beans to improve Web services performance

Shailesh K. Mishra (shailekm@in.ibm.com), Software Engineer, IBM, Software Group
Shailesh Mishra photo
Shailesh K. Mishra is a software engineer at India Software Lab, Gurgaon. He is currently working on business portlets as a developer of the IBM Portlet for Google Gadgets. His current area of interest is Web 2.0 technology in portals.

Summary:  Looking for ways to improve the performance of your Web services? Try asynchronous beans. This article explains how Web services access content from a variety of resources to perform business operations sequentially and how asynchronous beans can enhance this.

View more content in this series

Date:  16 Aug 2007
Level:  Intermediate
Activity:  2516 views

Introduction

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.Work interface. This is run in parallel with its caller using the WorkManager.startWork method.
  • AlarmListener is an object that implements the com.ibm.websphere.asynchbeans.AlarmListener interface. 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.


Conclusion

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.


Resources

Learn

Get products and technologies

  • Innovate your next development project with IBM trial software, available for download or on DVD.

Discuss

About the author

Shailesh Mishra photo

Shailesh K. Mishra is a software engineer at India Software Lab, Gurgaon. He is currently working on business portlets as a developer of the IBM Portlet for Google Gadgets. His current area of interest is Web 2.0 technology in portals.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and Web services
ArticleID=248438
ArticleTitle=Web services tip: Use asynchronous beans to improve Web services performance
publish-date=08162007
author1-email=shailekm@in.ibm.com
author1-email-cc=flanders@us.ibm.com

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers