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

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.

Share:

Shailesh K. Mishra, Software Engineer, IBM

Shailesh Mishra photoShailesh 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.



16 August 2007

Also available in Chinese Russian Japanese

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

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into SOA and web services on developerWorks


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