001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.activemq.jms.pool;
019
020import java.util.List;
021import java.util.concurrent.CopyOnWriteArrayList;
022import java.util.concurrent.atomic.AtomicBoolean;
023
024import javax.jms.Connection;
025import javax.jms.ExceptionListener;
026import javax.jms.IllegalStateException;
027import javax.jms.JMSException;
028import javax.jms.Session;
029import javax.jms.TemporaryQueue;
030import javax.jms.TemporaryTopic;
031
032import org.apache.commons.pool2.KeyedPooledObjectFactory;
033import org.apache.commons.pool2.PooledObject;
034import org.apache.commons.pool2.impl.DefaultPooledObject;
035import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
036import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
037import org.slf4j.Logger;
038import org.slf4j.LoggerFactory;
039
040/**
041 * Holds a real JMS connection along with the session pools associated with it.
042 * <p/>
043 * Instances of this class are shared amongst one or more PooledConnection object and must
044 * track the session objects that are loaned out for cleanup on close as well as ensuring
045 * that the temporary destinations of the managed Connection are purged when all references
046 * to this ConnectionPool are released.
047 */
048public class ConnectionPool implements ExceptionListener {
049    private static final transient Logger LOG = LoggerFactory.getLogger(ConnectionPool.class);
050
051    protected Connection connection;
052    private int referenceCount;
053    private long lastUsed = System.currentTimeMillis();
054    private final long firstUsed = lastUsed;
055    private boolean hasExpired;
056    private int idleTimeout = 30 * 1000;
057    private long expiryTimeout = 0l;
058    private boolean useAnonymousProducers = true;
059
060    private final AtomicBoolean started = new AtomicBoolean(false);
061    private final GenericKeyedObjectPool<SessionKey, SessionHolder> sessionPool;
062    private final List<PooledSession> loanedSessions = new CopyOnWriteArrayList<PooledSession>();
063    private boolean reconnectOnException;
064    private ExceptionListener parentExceptionListener;
065
066    public ConnectionPool(Connection connection) {
067        final GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig();
068        poolConfig.setJmxEnabled(false);
069        this.connection = wrap(connection);
070        try {
071            this.connection.setExceptionListener(this);
072        } catch (JMSException ex) {
073            LOG.warn("Could not set exception listener on create of ConnectionPool");
074        }
075
076        // Create our internal Pool of session instances.
077        this.sessionPool = new GenericKeyedObjectPool<SessionKey, SessionHolder>(
078            new KeyedPooledObjectFactory<SessionKey, SessionHolder>() {
079                @Override
080                public PooledObject<SessionHolder> makeObject(SessionKey sessionKey) throws Exception {
081
082                    return new DefaultPooledObject<SessionHolder>(new SessionHolder(makeSession(sessionKey)));
083                }
084
085                @Override
086                public void destroyObject(SessionKey sessionKey, PooledObject<SessionHolder> pooledObject) throws Exception {
087                    pooledObject.getObject().close();
088                }
089
090                @Override
091                public boolean validateObject(SessionKey sessionKey, PooledObject<SessionHolder> pooledObject) {
092                    return true;
093                }
094
095                @Override
096                public void activateObject(SessionKey sessionKey, PooledObject<SessionHolder> pooledObject) throws Exception {
097                }
098
099                @Override
100                public void passivateObject(SessionKey sessionKey, PooledObject<SessionHolder> pooledObject) throws Exception {
101                }
102            }, poolConfig
103        );
104    }
105
106    // useful when external failure needs to force expiry
107    public void setHasExpired(boolean val) {
108        hasExpired = val;
109    }
110
111    protected Session makeSession(SessionKey key) throws JMSException {
112        return connection.createSession(key.isTransacted(), key.getAckMode());
113    }
114
115    protected Connection wrap(Connection connection) {
116        return connection;
117    }
118
119    protected void unWrap(Connection connection) {
120    }
121
122    public void start() throws JMSException {
123        if (started.compareAndSet(false, true)) {
124            try {
125                connection.start();
126            } catch (JMSException e) {
127                started.set(false);
128                throw(e);
129            }
130        }
131    }
132
133    public synchronized Connection getConnection() {
134        return connection;
135    }
136
137    public Session createSession(boolean transacted, int ackMode) throws JMSException {
138        SessionKey key = new SessionKey(transacted, ackMode);
139        PooledSession session;
140        try {
141            session = new PooledSession(key, sessionPool.borrowObject(key), sessionPool, key.isTransacted(), useAnonymousProducers);
142            session.addSessionEventListener(new PooledSessionEventListener() {
143
144                @Override
145                public void onTemporaryTopicCreate(TemporaryTopic tempTopic) {
146                }
147
148                @Override
149                public void onTemporaryQueueCreate(TemporaryQueue tempQueue) {
150                }
151
152                @Override
153                public void onSessionClosed(PooledSession session) {
154                    ConnectionPool.this.loanedSessions.remove(session);
155                }
156            });
157            this.loanedSessions.add(session);
158        } catch (Exception e) {
159            IllegalStateException illegalStateException = new IllegalStateException(e.toString());
160            illegalStateException.initCause(e);
161            throw illegalStateException;
162        }
163        return session;
164    }
165
166    public synchronized void close() {
167        if (connection != null) {
168            try {
169                sessionPool.close();
170            } catch (Exception e) {
171            } finally {
172                try {
173                    connection.close();
174                } catch (Exception e) {
175                } finally {
176                    connection = null;
177                }
178            }
179        }
180    }
181
182    public synchronized void incrementReferenceCount() {
183        referenceCount++;
184        lastUsed = System.currentTimeMillis();
185    }
186
187    public synchronized void decrementReferenceCount() {
188        referenceCount--;
189        lastUsed = System.currentTimeMillis();
190        if (referenceCount == 0) {
191            // Loaned sessions are those that are active in the sessionPool and
192            // have not been closed by the client before closing the connection.
193            // These need to be closed so that all session's reflect the fact
194            // that the parent Connection is closed.
195            for (PooledSession session : this.loanedSessions) {
196                try {
197                    session.close();
198                } catch (Exception e) {
199                }
200            }
201            this.loanedSessions.clear();
202
203            unWrap(getConnection());
204
205            expiredCheck();
206        }
207    }
208
209    /**
210     * Determines if this Connection has expired.
211     * <p/>
212     * A ConnectionPool is considered expired when all references to it are released AND either
213     * the configured idleTimeout has elapsed OR the configured expiryTimeout has elapsed.
214     * Once a ConnectionPool is determined to have expired its underlying Connection is closed.
215     *
216     * @return true if this connection has expired.
217     */
218    public synchronized boolean expiredCheck() {
219
220        boolean expired = false;
221
222        if (connection == null) {
223            return true;
224        }
225
226        if (hasExpired) {
227            if (referenceCount == 0) {
228                close();
229                expired = true;
230            }
231        }
232
233        if (expiryTimeout > 0 && System.currentTimeMillis() > firstUsed + expiryTimeout) {
234            hasExpired = true;
235            if (referenceCount == 0) {
236                close();
237                expired = true;
238            }
239        }
240
241        // Only set hasExpired here is no references, as a Connection with references is by
242        // definition not idle at this time.
243        if (referenceCount == 0 && idleTimeout > 0 && System.currentTimeMillis() > lastUsed + idleTimeout) {
244            hasExpired = true;
245            close();
246            expired = true;
247        }
248
249        return expired;
250    }
251
252    public int getIdleTimeout() {
253        return idleTimeout;
254    }
255
256    public void setIdleTimeout(int idleTimeout) {
257        this.idleTimeout = idleTimeout;
258    }
259
260    public void setExpiryTimeout(long expiryTimeout) {
261        this.expiryTimeout = expiryTimeout;
262    }
263
264    public long getExpiryTimeout() {
265        return expiryTimeout;
266    }
267
268    public int getMaximumActiveSessionPerConnection() {
269        return this.sessionPool.getMaxTotalPerKey();
270    }
271
272    public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) {
273        this.sessionPool.setMaxTotalPerKey(maximumActiveSessionPerConnection);
274    }
275
276    public boolean isUseAnonymousProducers() {
277        return this.useAnonymousProducers;
278    }
279
280    public void setUseAnonymousProducers(boolean value) {
281        this.useAnonymousProducers = value;
282    }
283
284    /**
285     * @return the total number of Pooled session including idle sessions that are not
286     *          currently loaned out to any client.
287     */
288    public int getNumSessions() {
289        return this.sessionPool.getNumIdle() + this.sessionPool.getNumActive();
290    }
291
292    /**
293     * @return the total number of Sessions that are in the Session pool but not loaned out.
294     */
295    public int getNumIdleSessions() {
296        return this.sessionPool.getNumIdle();
297    }
298
299    /**
300     * @return the total number of Session's that have been loaned to PooledConnection instances.
301     */
302    public int getNumActiveSessions() {
303        return this.sessionPool.getNumActive();
304    }
305
306    /**
307     * Configure whether the createSession method should block when there are no more idle sessions and the
308     * pool already contains the maximum number of active sessions.  If false the create method will fail
309     * and throw an exception.
310     *
311     * @param block
312     *          Indicates whether blocking should be used to wait for more space to create a session.
313     */
314    public void setBlockIfSessionPoolIsFull(boolean block) {
315        this.sessionPool.setBlockWhenExhausted(block);
316    }
317
318    public boolean isBlockIfSessionPoolIsFull() {
319        return this.sessionPool.getBlockWhenExhausted();
320    }
321
322    /**
323     * Returns the timeout to use for blocking creating new sessions
324     *
325     * @return true if the pooled Connection createSession method will block when the limit is hit.
326     * @see #setBlockIfSessionPoolIsFull(boolean)
327     */
328    public long getBlockIfSessionPoolIsFullTimeout() {
329        return this.sessionPool.getMaxWaitMillis();
330    }
331
332    /**
333     * Controls the behavior of the internal session pool. By default the call to
334     * Connection.getSession() will block if the session pool is full.  This setting
335     * will affect how long it blocks and throws an exception after the timeout.
336     *
337     * The size of the session pool is controlled by the @see #maximumActive
338     * property.
339     *
340     * Whether or not the call to create session blocks is controlled by the @see #blockIfSessionPoolIsFull
341     * property
342     *
343     * @param blockIfSessionPoolIsFullTimeout - if blockIfSessionPoolIsFullTimeout is true,
344     *                                        then use this setting to configure how long to block before retry
345     */
346    public void setBlockIfSessionPoolIsFullTimeout(long blockIfSessionPoolIsFullTimeout) {
347        this.sessionPool.setMaxWaitMillis(blockIfSessionPoolIsFullTimeout);
348    }
349
350    /**
351     * @return true if the underlying connection will be renewed on JMSException, false otherwise
352     */
353    public boolean isReconnectOnException() {
354        return reconnectOnException;
355    }
356
357    /**
358     * Controls weather the underlying connection should be reset (and renewed) on JMSException
359     *
360     * @param reconnectOnException
361     *          Boolean value that configures whether reconnect on exception should happen
362     */
363    public void setReconnectOnException(boolean reconnectOnException) {
364        this.reconnectOnException = reconnectOnException;
365    }
366
367    ExceptionListener getParentExceptionListener() {
368        return parentExceptionListener;
369    }
370
371    void setParentExceptionListener(ExceptionListener parentExceptionListener) {
372        this.parentExceptionListener = parentExceptionListener;
373    }
374
375    @Override
376    public void onException(JMSException exception) {
377        if (isReconnectOnException()) {
378            close();
379        }
380        if (parentExceptionListener != null) {
381            parentExceptionListener.onException(exception);
382        }
383    }
384
385    @Override
386    public String toString() {
387        return "ConnectionPool[" + connection + "]";
388    }
389}