Asynchronous Servlet processing with Events in Java EE 6

Event based processing can be done on the following way in Java EE 6:


public class Sender {
@Inject Event<Message> messageEvent;

public void processAsync(Message message) {
messageEvent.fire(message);
}

public class Receiver {
public void asynchProcessor(@Observes Message message) {
// do your stuff
}
}

Servlets can be decoupled easier with the business code using the Observer pattern:

@WebServlet(name="myServlet", urlPatterns={"/asyncProcess"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
@Inject Event<AsyncContext> messageEvent;

public void doGet(AsyncContext asyncContext, HttpServletResponse response) {
AsyncContext asyncContext = asyncContext.startAsync(request, response);
messageEvent.fire(asyncContext);
}
}
public class Receiver {
public void asynchProcessor(@Observes AsyncContext asyncContext) {
// do your stuff
...
asyncContext.complete();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s