Contact Us 1-800-596-4880

Object Scopes

Determining How the Mule Container Deals with Objects

Scope (also referred to as cardinality) describes how the objects are created and managed in the Mule container.

Three Scopes

Three object scopes are defined in Mule:

  • Singleton - only one object is created for all requests

  • Prototype - a new object is created for every request or every time the object is requested from the registry

  • Pooled - Only applies to component objects, but these are stored in a pool that guarantees that only one thread will access an object at any one time.

Rules About Object Scopes

Singleton objects must be thread-safe, since multiple threads will be accessing the same object. Therefore, any member variables need to be guarded when writing to ensure only one thread at a time changes the data.

Objects that are given prototype scope are created for each request on the object, so the object does not need to be thread-safe, since there will only ever be one thread accessing it. However, the object must be stateless, since any member variables will only exist for the lifetime of the request.

Pooled objects are thread safe since Mule will guarantee that only one thread will access the object at a time. Pooled objects can’t easily maintain state on the object itself since there will be multiple instances created. The advantage of pooled over prototype is when the object may be expensive to create and creating a new instance for every message it receives will slow down the application.

When configuring Mule through XML Spring is used to translate the XML into objects that define how the Mule instance will run. All top-level objects in Mule are singletons including Service, Model, Connector, Endpoint, Agent, Security Manager, Transaction Manager. The only object that has prototype scope is Transformer (This is because transformers can be used in different contexts and potentially in different threads at the same time).

Components (POJO objects used by your service) can either be singleton, prototype or pooled.

Examples

Pooled

<pooled-component class="com.foo.Bar"/>

Singleton

<component >     <singleton-object class="com.foo.Bar"/></component>

Prototype

<component >     <prototype-object class="com.foo.Bar"></component><!—or short form --><component class="com.foo.Bar"/>

Spring scopes

Also you can reference a spring as a component where the scope of the object is defined by Spring -

<component >     <spring-object ref="myBean"></component>