Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,14 @@ public void endpointActivation(MessageEndpointFactory endpointFactory, Activatio
ActiveMQEndpointWorker worker = new ActiveMQEndpointWorker(this, key);

endpointWorkers.put(key, worker);
worker.start();
try {
worker.start();
} catch (ResourceException failure) {
synchronized (endpointWorkers) {
endpointWorkers.remove(key, worker);
}
throw failure;
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.apache.activemq.ra;

import java.lang.reflect.Method;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;

import jakarta.jms.JMSException;
Expand All @@ -25,11 +26,10 @@
import jakarta.jms.MessageProducer;
import jakarta.jms.ServerSession;
import jakarta.jms.Session;
import jakarta.resource.spi.UnavailableException;
import jakarta.resource.spi.endpoint.MessageEndpoint;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkEvent;
import jakarta.resource.spi.work.WorkException;
import jakarta.resource.spi.work.WorkListener;
import jakarta.resource.spi.work.WorkManager;

import org.apache.activemq.ActiveMQSession;
Expand Down Expand Up @@ -65,6 +65,7 @@ public class ServerSessionImpl implements ServerSession, InboundContext, Work, D
private MessageProducer messageProducer;
private final ServerSessionPoolImpl pool;

// Pool membership and changes to running are coordinated under the pool's sessionLock.
private final AtomicBoolean running = new AtomicBoolean(false);

/**
Expand Down Expand Up @@ -111,10 +112,22 @@ protected boolean isStale() {
return stale || !session.isRunning();
}

boolean isClosed() {
return session.isClosed();
}

protected boolean isRunning() {
return running.get();
}

void setRunning(boolean running) {
this.running.set(running);
}

boolean hasUnconsumedMessages() {
return session.hasUncomsumedMessages();
}

public MessageProducer getMessageProducer() throws JMSException {
if (messageProducer == null) {
messageProducer = getSession().createProducer(null);
Expand All @@ -127,37 +140,81 @@ public MessageProducer getMessageProducer() throws JMSException {
*/
public void start() throws JMSException {

if (!running.compareAndSet(false, true)) {
if (!pool.startSession(this)) {
log.debug("Start request ignored, already running.");
return; // already running
}

// We get here because we need to start a async worker.
log.debug("Starting run.");
scheduleWork(this, ActiveMQEndpointWorker.INITIAL_RETRY_DELAY);
}

private void scheduleWork(Work work, long retryDelay) throws JMSException {
try {
workManager.scheduleWork(this, WorkManager.INDEFINITE, null, new WorkListener() {
// The work listener is useful only for debugging...
public void workAccepted(WorkEvent event) {
log.debug("Work accepted: " + event);
WorkSubmission.schedule(workManager, work, failure -> {
try {
handleSchedulingFailure(failure, retryDelay);
} catch (JMSException error) {
// Late rejection cannot be thrown back through the submission call.
session.getConnection().onAsyncException(error);
}
});
} catch (WorkException | RejectedExecutionException failure) {
handleSchedulingFailure(failure, retryDelay);
}
}

public void workRejected(WorkEvent event) {
log.debug("Work rejected: " + event);
private void handleSchedulingFailure(Exception failure, long retryDelay) throws JMSException {
if (!pool.canRetry(this)) {
return;
}
if (WorkSubmission.isRetryable(failure)) {
try {
// running also reserves the session while a retry is pending, so later
// dispatches enqueue messages without submitting another worker.
if (pool.retryWork(() -> retryWork(retryDelay), retryDelay)) {
if (retryDelay == ActiveMQEndpointWorker.MAX_RETRY_DELAY) {
log.warn("WorkManager is still rejecting delivery work for {}; retrying in {} ms", this, retryDelay, failure);
} else {
log.debug("WorkManager rejected session work; retrying in {} ms", retryDelay, failure);
}
return;
}
} catch (UnavailableException timerFailure) {
failure.addSuppressed(timerFailure);
log.error("Unable to retry rejected session work", failure);
}
}
throw schedulingFailed(failure);
}

public void workStarted(WorkEvent event) {
log.debug("Work started: " + event);
}
private JMSException schedulingFailed(Exception failure) {
log.warn("Failed to schedule work for session {}, marking not running", this, failure);
pool.workSchedulingFailed(this);
return (JMSException) new JMSException("Start failed: " + failure).initCause(failure);
}

public void workCompleted(WorkEvent event) {
log.debug("Work completed: " + event);
private void retryWork(long delay) {
if (!pool.canRetry(this)) {
return;
}
try {
scheduleWork(new Work() {
@Override
public void run() {
// A submission already in flight cannot be recalled. Check again at
// execution so a closed or removed session cannot start delivery.
if (pool.canRetry(ServerSessionImpl.this)) {
ServerSessionImpl.this.run();
}
}

});
} catch (final WorkException e) {
log.warn("Failed to schedule work for session {}, marking not running", this, e);
running.set(false); // make sure we don't leave the ServerSession in a running state (misleading)
throw (JMSException)new JMSException("Start failed: " + e).initCause(e);
@Override
public void release() {
ServerSessionImpl.this.release();
}
}, ActiveMQEndpointWorker.nextRetryDelay(delay));
} catch (JMSException failure) {
session.getConnection().onAsyncException(failure);
}
}

Expand Down Expand Up @@ -192,14 +249,11 @@ public void run() {
// This endpoint may have gone stale due to error
if (stale) {
log.debug("Session {} stale, removing from pool", this);
running.set(false);
pool.removeFromPool(this);
break;
}
if (!session.hasUncomsumedMessages()) {
if (pool.returnToPoolIfIdle(this)) {
log.debug("Session {} has no unconsumed message, returning to pool", this);
running.set(false);
pool.returnToPool(this);
break;
} else {
log.debug("Session {} has more work to do b/c of unconsumed", this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,25 +204,100 @@ private ServerSessionImpl getExistingActiveServerSession() {
return ss;
}

boolean startSession(ServerSessionImpl ss) throws JMSException {
sessionLock.lock();
try {
if (closing.get()) {
throw new JMSException("Session Pool Shutting Down.");
}
if (ss.isRunning()) {
return false;
}
// A dispatcher can borrow an active session before the worker returns it to idle.
// Move it back to active before reserving it for a new run.
if (idleSessions.remove(ss)) {
activeSessions.add(ss);
} else if (!activeSessions.contains(ss)) {
throw new JMSException("Server session is no longer in the pool.");
}
ss.setRunning(true);
return true;
} finally {
sessionLock.unlock();
}
}

void workSchedulingFailed(ServerSessionImpl ss) {
sessionLock.lock();
try {
ss.setRunning(false);
} finally {
sessionLock.unlock();
}
}

boolean retryWork(Runnable retry, long delay) throws UnavailableException {
return activeMQAsfEndpointWorker.scheduleWorkRetry(retry, delay);
}

boolean canRetry(ServerSessionImpl ss) {
sessionLock.lock();
try {
return !closing.get() && activeSessions.contains(ss) && !ss.isClosed();
} finally {
sessionLock.unlock();
}
}

/**
* Returns a borrowed, non-running session to the pool if no messages are queued.
* A session still owned by a worker is returned by that worker instead.
*/
public void returnToPool(ServerSessionImpl ss) {
sessionLock.lock();
activeSessions.remove(ss);
try {
// make sure we only return non-stale sessions to the pool
if ( ss.isStale() ) {
if ( LOG.isDebugEnabled() ) {
LOG.debug("Discarding stale ServerSession to be returned to pool: " + ss);
}
ss.close();
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("ServerSession returned to pool: " + ss);
}
idleSessions.add(ss);
if (ss.isRunning() || ss.hasUnconsumedMessages() || !returnIdleSession(ss)) {
return;
}
} finally {
sessionLock.unlock();
}
notifySessionReturned();
}

boolean returnToPoolIfIdle(ServerSessionImpl ss) {
sessionLock.lock();
try {
// Dispatch enqueues before startSession takes this lock. If its start request
// was coalesced into this run, the message is already visible to this check.
if (ss.hasUnconsumedMessages()) {
return false;
}
ss.setRunning(false);
returnIdleSession(ss);
} finally {
sessionLock.unlock();
}
notifySessionReturned();
return true;
}

// Called with sessionLock held.
private boolean returnIdleSession(ServerSessionImpl ss) {
if (!activeSessions.remove(ss)) {
return false;
}
if (ss.isStale()) {
LOG.debug("Discarding stale ServerSession to be returned to pool: {}", ss);
ss.close();
} else {
LOG.debug("ServerSession returned to pool: {}", ss);
idleSessions.add(ss);
}
return true;
}

private void notifySessionReturned() {
synchronized (closing) {
closing.notify();
}
Expand All @@ -232,6 +307,7 @@ public void removeFromPool(ServerSessionImpl ss) {
sessionLock.lock();
try {
activeSessions.remove(ss);
ss.setRunning(false);
} finally {
sessionLock.unlock();
}
Expand Down
Loading
Loading