Skip to content
Merged
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
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ Starting with 4.0.1, every published JAR declares a stable `Automatic-Module-Nam
| `smtp-connection-pool-jakarta-provider` | `org.simplejavamail.smtpconnectionpool.jakarta` |
| `smtp-connection-pool-camel` | `org.simplejavamail.smtpconnectionpool.camel` |

The transitive object-pool chain is stable as well: `generic-object-pool 2.5.0` declares
`org.bbottema.genericobjectpool`, and `clustered-object-pool 4.1.0` declares
The transitive object-pool chain is stable as well: `generic-object-pool` declares
`org.bbottema.genericobjectpool`, and `clustered-object-pool` declares
`org.bbottema.clusteredobjectpool`. The build inspects every packaged manifest and compiles a real
module-path consumer requiring all five names.

Expand Down Expand Up @@ -325,6 +325,11 @@ Verification runs all module tests, the real-server demo smoke tests, SpotBugs,

[Simple Java Mail #699](https://github.com/bbottema/simple-java-mail/issues/699) may produce a faster physical transport. If it implements Jakarta Mail's synchronous `Transport` contract with one reusable physical session per instance, it can be selected beneath these paths just like Angus. If it instead uses Simple Java Mail's `CustomMailer`, it owns its own lifecycle and must not be stacked on this pool.

## Unreleased

- [#33](https://github.com/simple-java-mail/smtp-connection-pool/issues/33), [#34](https://github.com/simple-java-mail/smtp-connection-pool/pull/34): opt into age-based expiration with `mail.smtppool.pool.expiration-since-creation-millis` in the Jakarta provider and Camel adapter. The default `0` preserves the existing policy. Expiration is checked asynchronously while transports are available; it does not impose a hard connection-lifetime limit.
- Update to `clustered-object-pool 4.1.1`, bringing in the timeout-policy equality fix from `generic-object-pool 2.5.1`. Creation-age and last-claim rules retain separate expiry state even with identical thresholds, using the standard combined policy ([upstream fix](https://github.com/bbottema/generic-object-pool/issues/24)). Existing APIs, Java baselines and module names remain supported.

## Current release

`4.1.0` (8 September 2026)
Expand Down
6 changes: 6 additions & 0 deletions RELEASE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ https://github.com/simple-java-mail/smtp-connection-pool
RELEASE NOTES SMTP Connection Pool


Unreleased

- #33, #34: Add mail.smtppool.pool.expiration-since-creation-millis to the Jakarta provider and Camel configuration. The default 0 keeps age-based expiration disabled; negative values are rejected. Either the last-claim or creation-age threshold makes an available transport eligible for asynchronous retirement. Active leases are not expired, and rapid reuse can delay retirement beyond the threshold.
- #34: Update clustered-object-pool to 4.1.1 and transitively generic-object-pool to 2.5.1, fixing equality between different timeout-policy types with matching thresholds (bbottema/generic-object-pool#24, bbottema/generic-object-pool#25). Use the upstream CombinedExpirationPolicies so both rules and their expiry state remain distinct. Existing APIs, Java baselines and JPMS automatic module names remain supported.


v4.1.0 (08-Sep-2026)

- #31: Add opt-in ClaimOptions/ClaimControl on direct, keyed and load-balanced transport acquisition. One cooperative budget covers registration, selection, waiting and preparation, using clustered-object-pool 4.1.0 and generic-object-pool 2.5.0.
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
<license.owner.email>benny@bennybottema.com</license.owner.email>
<jakarta-mail.version>2.1.3</jakarta-mail.version>
<jakarta-activation.version>2.1.4</jakarta-activation.version>
<clustered-object-pool.version>4.1.0</clustered-object-pool.version>
<clustered-object-pool.version>4.1.1</clustered-object-pool.version>
<angus-mail.version>2.0.5</angus-mail.version>
<spring.version>6.2.19</spring.version>
<camel.version>4.22.0</camel.version>
Expand Down
13 changes: 13 additions & 0 deletions smtp-connection-pool-camel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ to("smtppool://smtp.example.com:2525"
+ "&username=user&password=secret&to=recipient@example.com");
```

Pool tuning properties reach the pool the same way. To make available transports eligible for retirement
15 minutes after creation, independently of their last claim:

```java
to("smtppool://smtp.example.com:587"
+ "?mail.smtppool.pool.expiration-since-creation-millis=900000"
+ "&username=user&password=secret&to=recipient@example.com");
```

Expiration is checked asynchronously while transports are available. Active leases are not interrupted, and rapid
reuse can delay retirement past the threshold. See the [provider configuration](../smtp-connection-pool-jakarta-provider/README.md#configuration-reference)
for the expiration settings and defaults.

Internally created Jakarta Mail Sessions are tracked and shut down gracefully when the Camel component stops. Camel waits up to 30 seconds; on timeout or interruption it escalates to forced shutdown and also waits for physical cleanup before stop returns. If an externally supplied Session is used, its owner must call `SmtpPoolRegistry.shutdown(session)`.

Ordinary Camel `smtp:`/`smtps:` components and ordinary Jakarta Mail `session.getTransport("smtp")` lookups are untouched. The adapter does not register `PooledTransport` as `smtp`; it asks Camel to use `smtppool` explicitly.
6 changes: 6 additions & 0 deletions smtp-connection-pool-jakarta-provider/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,15 @@ The resolver branch takes precedence over a configured `Provider`, which takes p
| `mail.smtppool.pool.max-size` | integer | `4` | Maximum physical connections per identity |
| `mail.smtppool.pool.claim-timeout-millis` | long | `30000` | Maximum wait for an exclusive lease |
| `mail.smtppool.pool.expiration-millis` | long | `10000` | Eligibility threshold measured since an available transport's last claim |
| `mail.smtppool.pool.expiration-since-creation-millis` | long | `0` | Eligibility threshold measured since an available pooled transport was created; `0` disables age-based expiration |

Provider and resolver values are objects placed with `Properties.put`, not strings loaded from a properties file.

When age-based expiration is enabled, either expiration threshold makes an available transport eligible for retirement.
The pool checks asynchronously and never expires an active lease. A transport can be reclaimed before it is checked,
so this setting does not impose a strict maximum connection lifetime or guarantee retirement before a server's age
limit. At the default `0`, the existing last-claim-only policy is used. Negative age thresholds are rejected.

Endpoint identity includes the Session-scoped manager, normalized delegate protocol and resolved provider metadata, host, effective port, username, and an HMAC credential fingerprint. Raw passwords/tokens are excluded from equality and `toString` and retained only while needed for reconnect/allocation. When credentials rotate, the new generation becomes current immediately; the superseded pool accepts no new claims, drains existing leases, and then clears its credential material and retained pool record. Remaining material is cleared on Session-pool shutdown.

Passwords supplied by Jakarta Mail and saved Session authentication are fingerprinted automatically. The configured OAuth token supplier is resolved for every pooled `connect`, so rotating a token creates a separate identity. If a custom authenticator rotates credentials without exposing the effective password, update `mail.smtppool.credential.identity` with its generation/version.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
import org.bbottema.clusteredobjectpool.core.ClusterConfig;
import org.bbottema.clusteredobjectpool.core.ResourceClusters;
import org.bbottema.clusteredobjectpool.core.api.ResourceKey.ResourceClusterAndPoolKey;
import org.bbottema.genericobjectpool.ExpirationPolicy;
import org.bbottema.genericobjectpool.PoolableObject;
import org.bbottema.genericobjectpool.expirypolicies.CombinedExpirationPolicies;
import org.bbottema.genericobjectpool.expirypolicies.TimeoutSinceCreationExpirationPolicy;
import org.bbottema.genericobjectpool.expirypolicies.TimeoutSinceLastAllocationExpirationPolicy;
import org.bbottema.genericobjectpool.util.Timeout;
import org.simplejavamail.smtpconnectionpool.SessionTransport;
Expand All @@ -22,6 +25,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Locale;
import java.util.Map;
Expand Down Expand Up @@ -74,16 +78,18 @@ public SmtpPoolManager(final Session session) {
SmtpPoolProperties.DEFAULT_CLAIM_TIMEOUT_MILLIS);
final long expiration = longProperty(SmtpPoolProperties.EXPIRATION_MILLIS,
SmtpPoolProperties.DEFAULT_EXPIRATION_MILLIS);
if (coreSize < 0 || maxSize < 1 || coreSize > maxSize || claimTimeout < 0 || expiration < 0) {
final long expirationSinceCreation = longProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS,
SmtpPoolProperties.DEFAULT_EXPIRATION_SINCE_CREATION_MILLIS);
if (coreSize < 0 || maxSize < 1 || coreSize > maxSize || claimTimeout < 0 || expiration < 0
|| expirationSinceCreation < 0) {
throw new IllegalArgumentException("Invalid smtppool sizing or timeout configuration");
}

allocatorFactory = new ProviderTransportAllocatorFactory(session);
final ClusterConfig<String, ConnectionPoolKey, SessionTransport> config =
ClusterConfig.<String, ConnectionPoolKey, SessionTransport>builder()
.allocatorFactory(allocatorFactory)
.defaultExpirationPolicy(new TimeoutSinceLastAllocationExpirationPolicy<SessionTransport>(
expiration, TimeUnit.MILLISECONDS))
.defaultExpirationPolicy(expirationPolicy(expiration, expirationSinceCreation))
.defaultCorePoolSize(coreSize)
.defaultMaxPoolSize(maxSize)
.claimTimeout(new Timeout(claimTimeout, TimeUnit.MILLISECONDS))
Expand Down Expand Up @@ -437,6 +443,25 @@ private void markSessionShuttingDown() {
}
}

/**
* Combines the idle threshold with an optional age-since-creation threshold. A transport expires when either
* rule matches; an age threshold of {@code 0} preserves the historical idle-only behaviour exactly.
*/
static ExpirationPolicy<SessionTransport> expirationPolicy(final long expirationMillis,
final long expirationSinceCreationMillis) {
final ExpirationPolicy<SessionTransport> idlePolicy =
new TimeoutSinceLastAllocationExpirationPolicy<SessionTransport>(expirationMillis,
TimeUnit.MILLISECONDS);
if (expirationSinceCreationMillis == 0L) {
return idlePolicy;
}
final Set<ExpirationPolicy<SessionTransport>> policies = new HashSet<ExpirationPolicy<SessionTransport>>();
policies.add(idlePolicy);
policies.add(new TimeoutSinceCreationExpirationPolicy<SessionTransport>(expirationSinceCreationMillis,
TimeUnit.MILLISECONDS));
return new CombinedExpirationPolicies<SessionTransport>(policies);
}

private static String firstNonBlank(final String... candidates) {
for (String candidate : candidates) {
if (candidate != null && !candidate.trim().isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public final class SmtpPoolProperties {
public static final String CLAIM_TIMEOUT_MILLIS = "mail.smtppool.pool.claim-timeout-millis";
/** Expiration threshold in milliseconds measured since an available transport's last claim. */
public static final String EXPIRATION_MILLIS = "mail.smtppool.pool.expiration-millis";
/**
* Expiration eligibility threshold in milliseconds since a pooled transport was created; {@code 0} disables it.
* Checked asynchronously while the transport is available, so this is not a strict connection-lifetime limit.
*/
public static final String EXPIRATION_SINCE_CREATION_MILLIS = "mail.smtppool.pool.expiration-since-creation-millis";

/** Default core pool size. */
public static final int DEFAULT_CORE_POOL_SIZE = 0;
Expand All @@ -40,6 +45,8 @@ public final class SmtpPoolProperties {
public static final long DEFAULT_CLAIM_TIMEOUT_MILLIS = 30_000L;
/** Default available-transport expiration threshold in milliseconds. */
public static final long DEFAULT_EXPIRATION_MILLIS = 10_000L;
/** Default age-based expiration threshold in milliseconds; {@code 0} keeps age-based expiration disabled. */
public static final long DEFAULT_EXPIRATION_SINCE_CREATION_MILLIS = 0L;

private SmtpPoolProperties() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,43 @@ void poolCapacityTimesOutASecondExclusiveClaimAndRecoversAfterRelease() throws E
assertEquals(1, FakeTransport.instances.get());
}

@Test
void ageBasedExpirationRetiresAnAvailableTransportBeforeTheIdleThreshold() throws Exception {
session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_MILLIS, "60000");
session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "50");
sendOnce("secret");
assertEquals(1, FakeTransport.instances.get());

// The idle threshold cannot fire within this window, so a retirement here can only come from the age rule.
final SmtpPoolManager manager = SmtpPoolRegistry.getOrCreate(session);
for (int attempt = 0; attempt < 200 && manager.getLiveTransportCount() > 0; attempt++) {
Thread.sleep(25L);
}
assertEquals(0, manager.getLiveTransportCount());

sendOnce("secret");
assertEquals(2, FakeTransport.instances.get());
}

@Test
void anUnsetAgeThresholdLeavesIdleOnlyExpirationBehaviourUnchanged() throws Exception {
session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_MILLIS, "60000");
sendOnce("secret");

final SmtpPoolManager manager = SmtpPoolRegistry.getOrCreate(session);
Thread.sleep(300L);

assertEquals(1, manager.getLiveTransportCount());
sendOnce("secret");
assertEquals(1, FakeTransport.instances.get());
}

@Test
void aNegativeAgeThresholdIsRejectedWhenTheManagerIsCreated() {
session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "-1");
assertThrows(IllegalArgumentException.class, () -> SmtpPoolRegistry.getOrCreate(session));
}

@Test
void interruptedPoolClaimPreservesTheWaiterInterruptFlag() throws Exception {
session.getProperties().setProperty(SmtpPoolProperties.MAX_POOL_SIZE, "1");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.simplejavamail.smtpconnectionpool.jakarta;

import org.bbottema.genericobjectpool.ExpirationPolicy;
import org.bbottema.genericobjectpool.PoolableObject;
import org.bbottema.genericobjectpool.expirypolicies.TimeoutSinceLastAllocationExpirationPolicy;
import org.junit.jupiter.api.Test;
import org.simplejavamail.smtpconnectionpool.SessionTransport;

import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class SmtpPoolManagerExpirationTest {

@Test
void equalThresholdsRetainTheCreationRuleAndSeparateExpiryState() {
final ExpirationPolicy<SessionTransport> policy = SmtpPoolManager.expirationPolicy(50L, 50L);
final PoolableObject<SessionTransport> transport = transportAged(50L, 0L);

assertTrue(policy.hasExpired(transport), "Only creation age has reached the shared threshold");
assertEquals(2, transport.getExpiriesMs().size(), "Both rules must keep their own expiry state");
}

@Test
void theIdleRuleStillExpiresBeforeTheCreationThreshold() {
final ExpirationPolicy<SessionTransport> policy = SmtpPoolManager.expirationPolicy(50L, 60_000L);
assertTrue(policy.hasExpired(transportAged(100L, 50L)));
}

@Test
void neitherRuleExpiresBeforeItsThreshold() {
final ExpirationPolicy<SessionTransport> policy = SmtpPoolManager.expirationPolicy(50L, 100L);
assertFalse(policy.hasExpired(transportAged(99L, 49L)));
}

@Test
void zeroCreationThresholdPreservesTheSingleIdlePolicy() {
final ExpirationPolicy<SessionTransport> policy = SmtpPoolManager.expirationPolicy(50L, 0L);
assertInstanceOf(TimeoutSinceLastAllocationExpirationPolicy.class, policy);
assertFalse(policy.hasExpired(transportAged(60_000L, 49L)));
assertTrue(policy.hasExpired(transportAged(60_000L, 50L)));
}

@SuppressWarnings({"unchecked", "rawtypes"})
private static PoolableObject<SessionTransport> transportAged(final long creationAge, final long lastClaimAge) {
final PoolableObject<SessionTransport> transport = mock(PoolableObject.class);
final Map<ExpirationPolicy, Long> expiryState = new HashMap<ExpirationPolicy, Long>();
when(transport.ageMs()).thenReturn(creationAge);
when(transport.allocationAgeMs()).thenReturn(lastClaimAge);
when(transport.getExpiriesMs()).thenReturn(expiryState);
return transport;
}
}