Fire And Forget. Without JMS. With EJB 3.1 and 8KB WAR File

JMS was often used just for asynchronous execution of synchronous methods. Now you can achieve the same with a single annotation: @Asynchronous. The following EJB 3.1 stores a JPA entity in an asynchronous way:

@Path("message")

@Stateless

public class MessagingService {


    @PersistenceContext

    EntityManager em;


    @POST

    @Asynchronous

    public void newMessage(String content){

        em.persist(new Message(content));

    }


    @Asynchronous

    public Future<Long> create(String content){

        Message message = new Message(content);

        em.persist(message);

        em.flush();

        em.refresh(message);

        return new AsyncResult<Long>(message.getId());

    }

} 

The method newMessage will be executed asynchronously, but still transactional, in the application servers thread pool.  The method create returns Future, and can return so a result. It will either be executed in background thread or synchronous - if you invoke it too early. So it doesn't fit exactly to the Fire And Forget paradigm.

A deployable, working example (project Fire And Forget) was tested with Glassfish v3b70 and NetBeans 6.8beta and pushed into http://kenai.com/projects/javaee-patterns/.  Btw. the whole WAR file (EJB 3.1 + REST) takes 8kB on the hard drive....

[See Lightweight Asynchronous Facade pattern, page 65 in "Real World Java EE Patterns Rethinking Best Practices" book for more in-depth discussion] 


Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

"It will either be executed in background thread or synchronous - if you invoke it too early. So it doesn't fit exactly to the Fire And Forget paradigm."
What do you mean by that: how can you invoke it too early ???

Posted by miluch on November 08, 2010 at 05:45 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License