Top Description Inners Fields Constructors Methods
org.springframework.jms.connection

public Class CachingConnectionFactory

extends SingleConnectionFactory
Class Inheritance
Imports
java.lang.reflect.InvocationHandler, .InvocationTargetException, .Method, .Proxy, java.util.ArrayDeque, .ArrayList, .Deque, .HashMap, .Iterator, .List, .Map, java.util.concurrent.ConcurrentHashMap, .ConcurrentMap, jakarta.jms.Connection, .ConnectionFactory, .Destination, .JMSException, .MessageConsumer, .MessageProducer, .QueueSession, .Session, .TemporaryQueue, .TemporaryTopic, .Topic, .TopicSession, org.springframework.lang.Nullable, org.springframework.util.Assert, .ClassUtils, .ObjectUtils

SingleConnectionFactory subclass that adds Session caching as well as MessageProducer and MessageConsumer caching. This ConnectionFactory also switches the "reconnectOnException" property to "true" by default, allowing for automatic recovery of the underlying Connection.

By default, only one single Session will be cached, with further requested Sessions being created and disposed on demand. Consider raising the "sessionCacheSize" value in case of a high-concurrency environment.

When using the JMS 1.0.2 API, this ConnectionFactory will switch into queue/topic mode according to the JMS API methods used at runtime: createQueueConnection and createTopicConnection will lead to queue/topic mode, respectively; generic createConnection calls will lead to a JMS 1.1 connection which is able to serve both modes.

As of Spring Framework 5, this class supports JMS 2.0 JMSContext calls and therefore requires the JMS 2.0 API to be present at runtime. It may nevertheless run against a JMS 1.1 driver (bound to the JMS 2.0 API) as long as no actual JMS 2.0 calls are triggered by the application's setup.

NOTE: This ConnectionFactory requires explicit closing of all Sessions obtained from its shared Connection. This is the usual recommendation for native JMS access code anyway. However, with this ConnectionFactory, its use is mandatory in order to actually allow for Session reuse.

Note also that MessageConsumers obtained from a cached Session won't get closed until the Session will eventually be removed from the pool. This may lead to semantic side effects in some cases. For a durable subscriber, the logical Session.close() call will also close the subscription. Re-registering a durable consumer for the same subscription on the same Session handle is not supported; close and reobtain a cached Session first.

Last but not least, MessageProducers and MessageConsumers for temporary queues and topics (TemporaryQueue/TemporaryTopic) will never be cached. Unfortunately, WebLogic JMS happens to implement the temporary queue/topic interfaces on its regular destination implementation, mis-indicating that none of its destinations can be cached. Please use a different connection pool/cache on WebLogic, or customize this class for WebLogic purposes.

Author
Juergen Hoeller
Since
2.5.3
See Also
Connection, Session, MessageProducer, MessageConsumer

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
CachingConnectionFactory.CachedSessionInvocationHandler

Invocation handler for a cached JMS Session proxy.

private static class
CachingConnectionFactory.ConsumerCacheKey

Simple wrapper class around a Destination and other consumer attributes.

private static class
CachingConnectionFactory.DestinationCacheKey

Simple wrapper class around a Destination reference.

Field Summary

Modifier and TypeField and Description
private volatile boolean
private boolean
private final ConcurrentMap<Integer, Deque<Session>>
private boolean
private int
Inherited from org.springframework.jms.connection.SingleConnectionFactory:
logger

Constructor Summary

AccessConstructor and Description
public
CachingConnectionFactory()

Create a new CachingConnectionFactory for bean-style usage.

public
CachingConnectionFactory(ConnectionFactory
the target ConnectionFactory
targetConnectionFactory
)

Create a new CachingConnectionFactory for the given target ConnectionFactory.

Method Summary

Modifier and TypeMethod and Description
public int
getCachedSessionCount()

Return a current session count, indicating the number of sessions currently cached by this connection factory.

protected Session

Returns:

the wrapped Session
getCachedSessionProxy
(Session
the original Session to wrap
target
,
Deque<Session>
the List of cached Sessions that the given Session belongs to
sessionList
)

Wrap the given Session with a proxy that delegates every method call to it but adapts close calls.

protected Session
getSession(Connection
the JMS Connection to operate on
con
,
Integer
the Session acknowledgement mode (Session.TRANSACTED or one of the common modes)
mode
)

Overrides org.springframework.jms.connection.SingleConnectionFactory.getSession.

Checks for a cached Session for the given mode.

public int
getSessionCacheSize()

Return the desired size for the JMS Session cache (per JMS Session type).

public boolean
isCacheConsumers()

Return whether to cache JMS MessageConsumers per JMS Session instance.

public boolean
isCacheProducers()

Return whether to cache JMS MessageProducers per JMS Session instance.

public void
public void
setCacheConsumers(boolean cacheConsumers)

Specify whether to cache JMS MessageConsumers per JMS Session instance (more specifically: one MessageConsumer per Destination, selector String and Session).

public void
setCacheProducers(boolean cacheProducers)

Specify whether to cache JMS MessageProducers per JMS Session instance (more specifically: one MessageProducer per Destination and Session).

public void
setSessionCacheSize(int sessionCacheSize)

Specify the desired size for the JMS Session cache (per JMS Session type).

Inherited from org.springframework.jms.connection.SingleConnectionFactory:
afterPropertiesSetcloseConnectioncreateConnectioncreateConnectioncreateContextcreateContextcreateContextcreateContextcreateQueueConnectioncreateQueueConnectioncreateSessioncreateTopicConnectioncreateTopicConnectiondestroydoCreateConnectiongetClientIdgetConnectiongetExceptionListenergetSharedConnectionProxygetTargetConnectionFactoryinitConnectionisReconnectOnExceptionisRunningonExceptionprepareConnectionsetClientIdsetExceptionListenersetReconnectOnExceptionsetTargetConnectionFactorystartstop

Field Detail

activeback to summary
private volatile boolean active
cacheConsumersback to summary
private boolean cacheConsumers
cachedSessionsback to summary
private final ConcurrentMap<Integer, Deque<Session>> cachedSessions
cacheProducersback to summary
private boolean cacheProducers
sessionCacheSizeback to summary
private int sessionCacheSize

Constructor Detail

CachingConnectionFactoryback to summary
public CachingConnectionFactory()

Create a new CachingConnectionFactory for bean-style usage.

See Also
setTargetConnectionFactory
CachingConnectionFactoryback to summary
public CachingConnectionFactory(ConnectionFactory targetConnectionFactory)

Create a new CachingConnectionFactory for the given target ConnectionFactory.

Parameters
targetConnectionFactory:ConnectionFactory

the target ConnectionFactory

Method Detail

getCachedSessionCountback to summary
public int getCachedSessionCount()

Return a current session count, indicating the number of sessions currently cached by this connection factory.

Since
5.3.7
getCachedSessionProxyback to summary
protected Session getCachedSessionProxy(Session target, Deque<Session> sessionList)

Wrap the given Session with a proxy that delegates every method call to it but adapts close calls. This is useful for allowing application code to handle a special framework Session just like an ordinary Session.

Parameters
target:Session

the original Session to wrap

sessionList:Deque<Session>

the List of cached Sessions that the given Session belongs to

Returns:Session

the wrapped Session

getSessionback to summary
protected Session getSession(Connection con, Integer mode) throws JMSException

Overrides org.springframework.jms.connection.SingleConnectionFactory.getSession.

Checks for a cached Session for the given mode.

Parameters
con:Connection

Doc from org.springframework.jms.connection.SingleConnectionFactory.getSession.

the JMS Connection to operate on

mode:Integer

Doc from org.springframework.jms.connection.SingleConnectionFactory.getSession.

the Session acknowledgement mode (Session.TRANSACTED or one of the common modes)

Returns:Session

Doc from org.springframework.jms.connection.SingleConnectionFactory.getSession.

the Session to use, or null to indicate creation of a raw standard Session

Annotations
@Override
Exceptions
JMSException:

Doc from org.springframework.jms.connection.SingleConnectionFactory.getSession.

if thrown by the JMS API

getSessionCacheSizeback to summary
public int getSessionCacheSize()

Return the desired size for the JMS Session cache (per JMS Session type).

isCacheConsumersback to summary
public boolean isCacheConsumers()

Return whether to cache JMS MessageConsumers per JMS Session instance.

isCacheProducersback to summary
public boolean isCacheProducers()

Return whether to cache JMS MessageProducers per JMS Session instance.

resetConnectionback to summary
public void resetConnection()

Overrides org.springframework.jms.connection.SingleConnectionFactory.resetConnection.

Resets the Session cache as well.

Annotations
@Override
setCacheConsumersback to summary
public void setCacheConsumers(boolean cacheConsumers)

Specify whether to cache JMS MessageConsumers per JMS Session instance (more specifically: one MessageConsumer per Destination, selector String and Session). Note that durable subscribers will only be cached until logical closing of the Session handle.

Default is "true". Switch this to "false" in order to always recreate MessageConsumers on demand.

setCacheProducersback to summary
public void setCacheProducers(boolean cacheProducers)

Specify whether to cache JMS MessageProducers per JMS Session instance (more specifically: one MessageProducer per Destination and Session).

Default is "true". Switch this to "false" in order to always recreate MessageProducers on demand.

setSessionCacheSizeback to summary
public void setSessionCacheSize(int sessionCacheSize)

Specify the desired size for the JMS Session cache (per JMS Session type).

This cache size is the maximum limit for the number of cached Sessions per session acknowledgement type (auto, client, dups_ok, transacted). As a consequence, the actual number of cached Sessions may be up to four times as high as the specified value - in the unlikely case of mixing and matching different acknowledgement types.

Default is 1: caching a single Session, (re-)creating further ones on demand. Specify a number like 10 if you'd like to raise the number of cached Sessions; that said, 1 may be sufficient for low-concurrency scenarios.

See Also
setCacheProducers
org.springframework.jms.connection back to summary

private Class CachingConnectionFactory.CachedSessionInvocationHandler

extends Object
implements InvocationHandler
Class Inheritance
  • java.lang.Object
  • org.springframework.jms.connection.CachingConnectionFactory.CachedSessionInvocationHandler
All Implemented Interfaces
java.lang.reflect.InvocationHandler

Invocation handler for a cached JMS Session proxy.

Field Summary

Modifier and TypeField and Description
private final Map<CachingConnectionFactory.ConsumerCacheKey, MessageConsumer>
private final Map<CachingConnectionFactory.DestinationCacheKey, MessageProducer>
private final Deque<Session>
private final Session
private boolean

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
private MessageConsumer
getCachedConsumer(Destination dest, String selector, Boolean noLocal, String subscription, boolean durable)

private MessageProducer
public Object
invoke(Object
the proxy instance that the method was invoked on
proxy
,
Method
the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.
method
,
Object[]
an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.
args
)

Implements java.lang.reflect.InvocationHandler.invoke.

Processes a method invocation on a proxy instance and returns the result.

private void
private void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

cachedConsumersback to summary
private final Map<CachingConnectionFactory.ConsumerCacheKey, MessageConsumer> cachedConsumers
cachedProducersback to summary
private final Map<CachingConnectionFactory.DestinationCacheKey, MessageProducer> cachedProducers
sessionListback to summary
private final Deque<Session> sessionList
targetback to summary
private final Session target
transactionOpenback to summary
private boolean transactionOpen

Constructor Detail

CachedSessionInvocationHandlerback to summary
public CachedSessionInvocationHandler(Session target, Deque<Session> sessionList)

Method Detail

getCachedConsumerback to summary
private MessageConsumer getCachedConsumer(Destination dest, String selector, Boolean noLocal, String subscription, boolean durable) throws JMSException
Annotations
@SuppressWarnings:resource
getCachedProducerback to summary
private MessageProducer getCachedProducer(Destination dest) throws JMSException
invokeback to summary
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable

Implements java.lang.reflect.InvocationHandler.invoke.

Doc from java.lang.reflect.InvocationHandler.invoke.

Processes a method invocation on a proxy instance and returns the result. This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with.

Parameters
proxy:Object

the proxy instance that the method was invoked on

method:Method

the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.

args:Object[]

an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.

Returns:Object

the value to return from the method invocation on the proxy instance. If the declared return type of the interface method is a primitive type, then the value returned by this method must be an instance of the corresponding primitive wrapper class; otherwise, it must be a type assignable to the declared return type. If the value returned by this method is null and the interface method's return type is primitive, then a NullPointerException will be thrown by the method invocation on the proxy instance. If the value returned by this method is otherwise not compatible with the interface method's declared return type as described above, a ClassCastException will be thrown by the method invocation on the proxy instance.

Annotations
@Override
@Nullable
Exceptions
Throwable:
the exception to throw from the method invocation on the proxy instance. The exception's type must be assignable either to any of the exception types declared in the throws clause of the interface method or to the unchecked exception types java.lang.RuntimeException or java.lang.Error. If a checked exception is thrown by this method that is not assignable to any of the exception types declared in the throws clause of the interface method, then an UndeclaredThrowableException containing the exception that was thrown by this method will be thrown by the method invocation on the proxy instance.
logicalCloseback to summary
private void logicalClose(Session proxy) throws JMSException
physicalCloseback to summary
private void physicalClose() throws JMSException
org.springframework.jms.connection back to summary

private Class CachingConnectionFactory.ConsumerCacheKey

extends DestinationCacheKey
Class Inheritance

Simple wrapper class around a Destination and other consumer attributes. Used as the cache key when caching MessageConsumer objects.

Field Summary

Modifier and TypeField and Description
private final boolean
private final Boolean
private final String
private final String

Constructor Summary

AccessConstructor and Description
public
ConsumerCacheKey(Destination destination, String selector, Boolean noLocal, String subscription, boolean durable)

Method Summary

Modifier and TypeMethod and Description
public boolean
equals(Object
the reference object with which to compare.
other
)

Overrides org.springframework.jms.connection.CachingConnectionFactory.DestinationCacheKey.equals.

Indicates whether some other object is "equal to" this one.

public int
public String
Inherited from org.springframework.jms.connection.CachingConnectionFactory.DestinationCacheKey:
compareTodestinationEquals

Field Detail

durableback to summary
private final boolean durable
noLocalback to summary
private final Boolean noLocal
Annotations
@Nullable
selectorback to summary
private final String selector
Annotations
@Nullable
subscriptionback to summary
private final String subscription
Annotations
@Nullable

Constructor Detail

ConsumerCacheKeyback to summary
public ConsumerCacheKey(Destination destination, String selector, Boolean noLocal, String subscription, boolean durable)

Method Detail

equalsback to summary
public boolean equals(Object other)

Overrides org.springframework.jms.connection.CachingConnectionFactory.DestinationCacheKey.equals.

Doc from java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

Parameters
other:Object

the reference object with which to compare.

Returns:boolean

true if this object is the same as the obj argument; false otherwise.

Annotations
@Override
hashCodeback to summary
public int hashCode()

Overrides org.springframework.jms.connection.CachingConnectionFactory.DestinationCacheKey.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for this object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Returns:int

a hash code value for this object

Annotations
@Override
toStringback to summary
public String toString()

Overrides org.springframework.jms.connection.CachingConnectionFactory.DestinationCacheKey.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Returns:String

a string representation of the object

Annotations
@Override
org.springframework.jms.connection back to summary

private Class CachingConnectionFactory.DestinationCacheKey

extends Object
implements Comparable<CachingConnectionFactory.DestinationCacheKey>
Class Inheritance
  • java.lang.Object
  • org.springframework.jms.connection.CachingConnectionFactory.DestinationCacheKey
All Implemented Interfaces
java.lang.Comparable
Known Direct Subclasses
org.springframework.jms.connection.CachingConnectionFactory.ConsumerCacheKey

Simple wrapper class around a Destination reference. Used as the cache key when caching MessageProducer objects.

Field Summary

Modifier and TypeField and Description
private final Destination
private String

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public int
compareTo(CachingConnectionFactory.DestinationCacheKey
the object to be compared.
other
)

Implements java.lang.Comparable.compareTo.

Compares this object with the specified object for order.

protected boolean
public boolean
equals(Object
the reference object with which to compare.
other
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

private String
public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for this object.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

destinationback to summary
private final Destination destination
destinationStringback to summary
private String destinationString
Annotations
@Nullable

Constructor Detail

DestinationCacheKeyback to summary
public DestinationCacheKey(Destination destination)

Method Detail

compareToback to summary
public int compareTo(CachingConnectionFactory.DestinationCacheKey other)

Implements java.lang.Comparable.compareTo.

Doc from java.lang.Comparable.compareTo.

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

The implementor must ensure signum(x.compareTo(y)) == -signum(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception if and only if y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z) > 0.

Finally, the implementor must ensure that x.compareTo(y)==0 implies that signum(x.compareTo(z)) == signum(y.compareTo(z)), for all z.

Parameters
other:CachingConnectionFactory.DestinationCacheKey

the object to be compared.

Returns:int

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Annotations
@Override
destinationEqualsback to summary
protected boolean destinationEquals(CachingConnectionFactory.DestinationCacheKey otherKey)
equalsback to summary
public boolean equals(Object other)

Overrides java.lang.Object.equals.

Doc from java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

Parameters
other:Object

the reference object with which to compare.

Returns:boolean

true if this object is the same as the obj argument; false otherwise.

Annotations
@Override
getDestinationStringback to summary
private String getDestinationString()
hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for this object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Returns:int

a hash code value for this object

Annotations
@Override
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Returns:String

a string representation of the object

Annotations
@Override