javajakarta-eesynchronizationmessage-driven-bean

Synchronizing access to a MDB method across instances


I have an Message Driven Bean, which receives Audit messages. These messages also have information about the system being audited. When a message is received, the MDB can create the system if it does not exists or reuse an existing system.

My challenge is that when a lot of messages from a new system are received simultaneously, multiple MDB instances are created and can end up creating duplicate systems. Adding a constraint to the database is one way to solve it. Is there a way of avoiding these duplicates in the application, MDB in this case?


Solution

  • You could try something like this:

    private Object LOCK;
    public void onMessage() {
        code…
        synchronized(LOCK) {
            check if system exists, create if necessary
        }
        more code…
    }