Over a million developers have joined DZone.

Implementing Shared Variables in Mule

Want to share your data across a project? See how you can create and implement shared variables in Mule to do just that using singleton Java POJOs.

· Integration Zone

Learn how API management supports better integration in Achieving Enterprise Agility with Microservices and API Management, brought to you in partnership with 3scale

Ever wondered why session variables can't be shared across JMS transports?

I was trying to receive messages from a JMS Queue and, in case of an error, increment a counter until a threshold limit is reached. 

I tried setting a session variable in case of an exception and then incrementing it with:

<set-session-variable variableName="errorCounter" value="#[((sessionVars['errorCounter'] == null) ? 0 : sessionVars['errorCounter']) + new Integer(1).intValue()]"doc:name="Error Counter"/>

But as soon as the next thread of JMS Receiver starts, the session variable value is lost — it's null again.

The Workaround

  1. Create a POJO Java class with all the values we want to get and set in our Mule flows lying in the same project.

  2. Let's create a ErrorCounter.java class under src/main/java under the org.mule.utils package.

  3. package org.mule.utils;
    public class ErrorCounter {
        int errorCounter = 0;
        public int increment()
            return errorCounter;

    We can create getters and setters here, as we do in a JAVA POJO, and modify those functions as per our requirements.

  4. Next, create a singleton spring-bean instantiating the above class in your mule-config xml file.

        <spring:bean id="ErrorCounter" name="ErrorCounter"scope="singleton" class="org.mule.utils.ErrorCounter"/>

  5. Access these variables in mule flows using expressions to get and set the values. In this case, I am storing the value into a flow variable, which will have the value incremented when the next JMS Message is received.

    <set-variable variableName="errorCounter" value="#[app.registry['ErrorCounter'].increment();]" doc:name="Increment-Counter"/>

Hope this Helps. Thanks for reading!

Unleash the power of your APIs with future-proof API management - Create your account and start your free trial today, brought to you in partnership with 3scale.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}