Few days ago, during our regular code review, one of my colleagues raised a question what would happen — and if it’s even possible — when a CDI Observer (so a method with parameter annotated @Observes) would be invoked multiple times at the same time for different event instances. In other words, after producing few events, is it possible that the following method will be processed by more than one thread at the same time:

public void observe(@Observes MyEvent myEvent) { ... }

After thinking about it I’ve decided to run a few tests and describe results in this post.

First results: it occurred that CDI Events are fired in synchronous mode which was a bit surprise for me. Why?

Up to this time, I’ve seen it this way: CDI observers allows me to very cleanly separate event producer from event consumer, so I don’t have any hard-coded registering of listeners, maintaining a list of listeners and manually informing them. The CDI container does everything for me.

Therefore, if we have cleanly separated producers from consumers I thought that there exists some kind of event bus running in specialized, thread executors pool which is responsible for mediation between registered events and invoked observers methods. I guess I based this assumption on other event/listeners solutions like Google Guava EventBus. They give you a chance to define if you want to use synchronous (default, EventBus) or asynchronous event dispatchers (AsyncEventBus.)

Moreover, if EJBs are both: producer and consumer, I assume it would have the same features as asynchronous EJB calls when it comes to transactions. The only possible JTA transaction attribute for asynchronous event observer would be: REQUIRED, REQUIRES_NEW or NOT_SUPPORTED.

Now that’s all how I expected it to work which seems to be quite different from the current status. The real life shows that CDI events are synchronous.

There is an issue for making asynchronous events available in CDI 1.1 but I’m not sure what is the current status of this feature and didn’t find a word about it in CDI 1.1 (part of Java EE 7).

Let’s see how we can deal with it on our own.

Continue reading

Java Community Process

Java EE 7 has been recently accepted by the Executive Committee. This means that soon we should have Java EE 7 application servers available on the market. One of the specifications that constitutes Java EE 7 is JMS 2.0. Some interesting improvements were introduced since version 1.1.

JMS has a lot of weird stuff like: Connection#createSession(boolean transacted, int acknowledgeMode) method.

First method argument (transacted) defines if the session should be transacted. Java EE applications have JTA that takes care of transactions. We can choose if transactions are supported (default) or not. So why do we need this argument then?

Second method argument (acknowledgeMode) is an integer constant taken from Session object. Seriously, integers constants makes the API seems sooo legacy.

Finally, what is a meaning of those parameters in Java EE environment? JavaDoc says that acknowledgeMode is ignored if the session is transacted.

What does it all means? Nothing less than: those arguments doesn’t have any sense for JMS producer used in Java EE context. That’s why they encourage you to use (true, 0) parameter values to avoid unnecessary confusion.

This smells of legacy.

Ok, but let’s get back to the main subject. I wanted to take a look what’s new in JMS world and how it allows me to code easier and in more maintainable way. I’ve prepared a simple web application that uses JMS 2.0, JAX-RS and EJB (SLSB and MDB) and pushed it to my github repository here.

Continue reading

This post will talk about possible ways of defining EJB views using annotations (I’ll just mention about using EJB Deployment Descriptor at the end.) I’ll focus on the most current EJB 3.1 views omitting legacy local, remote and home interfaces. Therefore, we can choose between:

  • remote business interface view,
  • local business interface view,
  • no-interface view.

I won’t discuss functional differences between those views but rather focus on possible ways of defining them.

Continue reading

Let’s start with a short quiz. TxMergeBean is a SLSB that uses CMT and EntityManager. Assume the following local and remote business interfaces:

public interface TxMergeCommon {
    void methodA();
    void methodB(MeineEntity entity);
}

@Local
public interface TxMergeLocal {}

@Remote
public interface TxMergeRemote {} 

and the following SLSB:

@Stateless
public class TxMergeBean implements TxMergeRemote, TxMergeLocal {

    @PersistenceContext
    private EntityManager em;

    @EJB
    private TxMergeLocal self;

    @Resource
    private SessionContext sctx;

    public void methodA() {
        MeineEntity entity = new MeineEntity("methodA");
        em.persist(entity);

        self.methodB(entity);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void methodB(final MeineEntity entity) {
        entity.setName("methodB");
        em.merge(entity);

        sctx.setRollbackOnly();
    }
}

Assume that MeineEntity is properly defined and its only constructor parameter is saved as ‘name’ attribute.

What will be the database persisted value of MeinEntity ‘name’ attribute after TxMergeBean#methodA() invocation?

Continue reading

Being in EJB and JPA world using CMT (Container Managed Transactions) is very comfortable. Just define few annotations to demarcate transaction boundary (or use the defaults) and that’s it – no fiddling with manual begin, commit or rollback operations.
One way to rollback your transaction is to throw non-application exception (or application exception with rollback = true) from your EJB’s business method.

It seems simple: if during some operation there is a possibility that an exception will be thrown and you don’t want to rollback your tx than you should just catch this exception and you’re fine. You can now retry the volatile operation once again within the same, still active transaction.

Now its all true for application exceptions thrown from user’s components. The question is – what with exceptions thrown from other components? Like JPA’s EntityManager throwing a PersistenceException?

And that’s where the story begins.

Continue reading

UPDATE (5.08.2013) – I’ve updated this post to support JBoss EAP 6.1 Final (JBoss AS 7.2). Enjoy

UPDATE (2.09.2013) – Bela Ban pointed to his very interesting post about new ForkChannel feature and easy channel hijacking directly from JBoss AS / Infinispan. Read about it here

JGroups is Bela Ban‘s piece of software for reliable message exchange that is highly configurable and can use either TCP or UDP as a transport protocol. Basically – you run the JGroups on number of clients, they form a cluster and they can send and receive messages within the cluster.

jgroups_logo_450px

JGroups is used internally by JBoss Infinispan. Infinispan, however, unlike JGroups adds the distributed cache semantics (replicated / distributed modes, entries invalidation, transactional behavior, Map access API, etc.) It even allows you to use the cluster as a compute grid.

Infinispan in turn is used to provide JBoss AS 7 clustering functionalities. Therefore, it means that the underlying JGroups subsystem can and is configured using a standard JBoss AS 7 standalone*.xml file. You can access Infinispan cache from your Java EE component (e.g. EJB) without any problems as described here.

However, there are cases when you’d like to use just the underlying JGroups messaging instead of all the cache semantics Infinispan gives you. And here’s the place things are becoming more complicated. You can always use JGroups directly and store the configuration for it as an application-local resources. It might become arguable if this is or isn’t a violation of the Java EE spec which says that an application should not manage low-level connections, spawn threads, open sockets, etc. This is something that is better to be left to the application server – it also allows us to use one configuration file instead of spreading it across multiple places.

So, the question is – how to access the JGroups subsystem from our EJB application? The whole solution involves few steps which will be described below.

Continue reading

JPA specification defines few types of EntityManagers / Persistence Contexts. We can have:

  • extended and transactional-scoped EntityManagers,
  • container-managed or application-managed EntityManagers.
  • JTA or resource-local EntityManager,

Besides the above distinction, we also have two main contexts in which EntityManager / Persistence Context can exist – Java EE and Java SE. Not every option is available for Java EE and not every is possible in Java SE. In the rest of the post I refer to the Java EE environment.

Ok, so before we’ll proceed to the real topic of this post — which is the behaviour of the EntityManager in Java EE created manually using EntityManagerFactory — let’s just shortly describe the above EM types.

Continue reading

This post describes some of the pitfalls when coping with intercommunication between different modules (EAR, WAR, EJB-JAR) deployed in the same Java EE 6 Application Server.

The problem

The problem is as follows: you have two modules (let’s take the EARs as an example) that are deployed in the same JVM / Application Server: App1.ear and App2.ear.

App1.ear contains:

  • service.jar; it’s an EJB-JAR with the business logic of the application,
  • service-api.jar; it’s an API for the service.jar, so the EJB’s in service.jar must implement this API.

App2.ear contains:

  • client.jar; it’s the EJB-JAR with the business logic of the client application,
  • service-api.jar; it’s the same API / interfaces as in App1.ear/service-api.jar. It’s here because you will need to know the API of the service.jar if you want to communicate with it.

Continue reading

Java EE 6 brings a lot new features. Among the others there is the concept of profiles. Java EE starts with the definition of two: Full and Web Profile.

The idea is to create separate and more specialized set of services that better suits your job. E.g. if you only want to use Servlets, JSP and add some EJB’s – do you really need full-blown application server with JMS, JMX, CORBA, JAX-WS and a lot of other abbreviations?

If not, then perhaps the Web Profile is enough for you. If you need those additional services like remote EJB, JAX-RS (this one is a bit awkward and it’s possible it’ll be moved to the Web Profile in EE 7), Timers, etc. – then you probably should go with the Full Profile.

The point is – you have the choice. Moreover, the application server vendors can create their software to support only the particular profile – it’s supposed to lower the barrier for introducing new application severs to the market.

So, if we have Full and Web Profile, we should now be able to deploy our applications using not only EAR (Enterprise ARchive) as in pre Java EE 6 days but we should also be able to use WAR (Web ARchive). And in fact it is possible – you can deploy your Java EE 6 application using WAR.

Now, you might think that because the WAR is for Web Archives, it’s mainly for the Web Profile. At the same time EAR is for Enterprise Application Archive, so for Full Profile.

And there is nothing wrong with this thinking – it’s intuitive and it’s right.

However, it’s worth realizing that the EAR and WAR are just a matter of packaging. It’s not the definition of what profile am I using. In other words, e.g. I can use all Full Java EE Profile services with the WAR packaging format. You can deploy your application that uses Timers, Remote EJBs and others, wrap it in the WAR and deploy it – and that’s perfectly fine.

The bottom line is: the Web and Full Profile are for definition of what services need to be provided; the packaging of your application doesn’t declare what services you’ll be using.