From 3ed5440c5b6bba3ec087f7d37a3c0fd67820473e Mon Sep 17 00:00:00 2001 From: Gerrit Hageman <61193781+Gerrit23@users.noreply.github.com> Date: Thu, 17 Sep 2026 18:31:58 +0200 Subject: [PATCH 1/3] feat(pool): add age-based transport expiration property (#33) Only idle-based expiration was selectable. A transport that is claimed often enough never becomes idle long enough for TimeoutSinceLastAllocationExpirationPolicy to retire it, so a pool cannot respect a server that caps how long a connection may live regardless of activity. Exchange Online, for example, resets an SMTP connection after 20 minutes even in the middle of a send. Add mail.smtppool.pool.expiration-since-creation-millis. A transport now expires when either the idle rule or the age rule matches. The default of 0 disables the age rule and preserves the existing behaviour exactly. CombinedExpirationPolicies is deliberately not used to combine the two rules. It holds its members in a Set, while TimeoutExpirationPolicy derives equality from expiryAgeMs alone and its subclasses add no equality of their own, so an idle threshold and an age threshold configured to the same number of milliseconds compare equal and one rule is silently dropped. A small private policy combines the two instead. Reported separately as bbottema/generic-object-pool#24. --- .../jakarta/SmtpPoolManager.java | 53 +++++++++++++++++-- .../jakarta/SmtpPoolProperties.java | 4 ++ .../PooledTransportIntegrationTest.java | 47 ++++++++++++++++ 3 files changed, 101 insertions(+), 3 deletions(-) diff --git a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java index 66d9f9c..965ce97 100644 --- a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java +++ b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java @@ -10,7 +10,9 @@ 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.TimeoutSinceCreationExpirationPolicy; import org.bbottema.genericobjectpool.expirypolicies.TimeoutSinceLastAllocationExpirationPolicy; import org.bbottema.genericobjectpool.util.Timeout; import org.simplejavamail.smtpconnectionpool.SessionTransport; @@ -74,7 +76,10 @@ 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"); } @@ -82,8 +87,7 @@ public SmtpPoolManager(final Session session) { final ClusterConfig config = ClusterConfig.builder() .allocatorFactory(allocatorFactory) - .defaultExpirationPolicy(new TimeoutSinceLastAllocationExpirationPolicy( - expiration, TimeUnit.MILLISECONDS)) + .defaultExpirationPolicy(expirationPolicy(expiration, expirationSinceCreation)) .defaultCorePoolSize(coreSize) .defaultMaxPoolSize(maxSize) .claimTimeout(new Timeout(claimTimeout, TimeUnit.MILLISECONDS)) @@ -437,6 +441,49 @@ 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. + *

+ * {@code CombinedExpirationPolicies} is deliberately not used here: it holds its members in a {@link java.util.Set}, + * while {@code TimeoutExpirationPolicy} derives equality from {@code expiryAgeMs} alone and its subclasses add no + * equality of their own. Two different rules configured to the same number of milliseconds therefore compare equal + * and one of them is silently dropped from the set. + */ + private static ExpirationPolicy expirationPolicy(final long expirationMillis, + final long expirationSinceCreationMillis) { + final ExpirationPolicy idlePolicy = + new TimeoutSinceLastAllocationExpirationPolicy(expirationMillis, + TimeUnit.MILLISECONDS); + if (expirationSinceCreationMillis == 0L) { + return idlePolicy; + } + return new EitherExpirationPolicy(idlePolicy, + new TimeoutSinceCreationExpirationPolicy(expirationSinceCreationMillis, + TimeUnit.MILLISECONDS)); + } + + /** Expires a pooled object as soon as either of two independent rules considers it expired. */ + private static final class EitherExpirationPolicy implements ExpirationPolicy { + private final ExpirationPolicy first; + private final ExpirationPolicy second; + + EitherExpirationPolicy(final ExpirationPolicy first, final ExpirationPolicy second) { + this.first = first; + this.second = second; + } + + @Override + public boolean hasExpired(final PoolableObject poolableObject) { + return first.hasExpired(poolableObject) || second.hasExpired(poolableObject); + } + + @Override + public String toString() { + return "EitherExpirationPolicy(" + first + ", " + second + ")"; + } + } + private static String firstNonBlank(final String... candidates) { for (String candidate : candidates) { if (candidate != null && !candidate.trim().isEmpty()) { diff --git a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java index 0446e2e..10a6d42 100644 --- a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java +++ b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java @@ -31,6 +31,8 @@ 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 threshold in milliseconds measured since a physical transport was created; {@code 0} disables it. */ + 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; @@ -40,6 +42,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() { } diff --git a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java index 272f9be..db63437 100644 --- a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java +++ b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java @@ -484,6 +484,53 @@ void poolCapacityTimesOutASecondExclusiveClaimAndRecoversAfterRelease() throws E assertEquals(1, FakeTransport.instances.get()); } + @Test + void ageBasedExpirationRetiresATransportThatNeverStaysIdleLongEnoughToExpire() 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()); + } + + // Identical thresholds must keep both rules in force. A set-based combination cannot express that: the timeout + // policies derive equality from their millisecond value alone, so equal thresholds collapse into a single rule. + @Test + void identicalIdleAndAgeThresholdsStillRetireATransport() throws Exception { + session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_MILLIS, "50"); + session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "50"); + sendOnce("secret"); + + final SmtpPoolManager manager = SmtpPoolRegistry.getOrCreate(session); + for (int attempt = 0; attempt < 200 && manager.getLiveTransportCount() > 0; attempt++) { + Thread.sleep(25L); + } + + assertEquals(0, manager.getLiveTransportCount()); + } + @Test void interruptedPoolClaimPreservesTheWaiterInterruptFlag() throws Exception { session.getProperties().setProperty(SmtpPoolProperties.MAX_POOL_SIZE, "1"); From 1c2046bba8b1f5e4b3e4f100fa16036a5b694e66 Mon Sep 17 00:00:00 2001 From: Gerrit Hageman <61193781+Gerrit23@users.noreply.github.com> Date: Thu, 17 Sep 2026 18:31:58 +0200 Subject: [PATCH 2/3] docs(readme): document age-based transport expiration (#33) [skip ci] Add the new property to the provider configuration reference, and show in the Camel adapter README how to set it from a smtppool:// URI, since mail.* endpoint options already reach the Session. --- smtp-connection-pool-camel/README.md | 10 ++++++++++ smtp-connection-pool-jakarta-provider/README.md | 1 + 2 files changed, 11 insertions(+) diff --git a/smtp-connection-pool-camel/README.md b/smtp-connection-pool-camel/README.md index 60d0d5b..31aaeaa 100644 --- a/smtp-connection-pool-camel/README.md +++ b/smtp-connection-pool-camel/README.md @@ -43,6 +43,16 @@ to("smtppool://smtp.example.com:2525" + "&username=user&password=secret&to=recipient@example.com"); ``` +Pool tuning properties reach the pool the same way. Servers that enforce a maximum connection lifetime — Exchange +Online resets a connection after 20 minutes regardless of activity — need the age-based threshold, because a +continuously used connection never becomes idle long enough for the idle threshold to retire it: + +```java +to("smtppool://smtp.example.com:587" + + "?mail.smtppool.pool.expiration-since-creation-millis=900000" + + "&username=user&password=secret&to=recipient@example.com"); +``` + 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. diff --git a/smtp-connection-pool-jakarta-provider/README.md b/smtp-connection-pool-jakarta-provider/README.md index 5483bfb..9bd1040 100644 --- a/smtp-connection-pool-jakarta-provider/README.md +++ b/smtp-connection-pool-jakarta-provider/README.md @@ -93,6 +93,7 @@ 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 a 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. From 0bd26ffaac0872b49fd945a58d1d5fe22ff94998 Mon Sep 17 00:00:00 2001 From: bbottema Date: Thu, 17 Sep 2026 21:06:55 +0200 Subject: [PATCH 3/3] fix(provider): use upstream combined expiration policies --- README.md | 9 ++- RELEASE.txt | 6 ++ pom.xml | 2 +- smtp-connection-pool-camel/README.md | 9 ++- .../README.md | 7 ++- .../jakarta/SmtpPoolManager.java | 40 +++---------- .../jakarta/SmtpPoolProperties.java | 5 +- .../PooledTransportIntegrationTest.java | 18 ++---- .../SmtpPoolManagerExpirationTest.java | 59 +++++++++++++++++++ 9 files changed, 102 insertions(+), 53 deletions(-) create mode 100644 smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManagerExpirationTest.java diff --git a/README.md b/README.md index 40bff7e..5f9a0bc 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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) diff --git a/RELEASE.txt b/RELEASE.txt index 310ebbe..25ef956 100644 --- a/RELEASE.txt +++ b/RELEASE.txt @@ -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. diff --git a/pom.xml b/pom.xml index f0acf21..9bb9609 100644 --- a/pom.xml +++ b/pom.xml @@ -37,7 +37,7 @@ benny@bennybottema.com 2.1.3 2.1.4 - 4.1.0 + 4.1.1 2.0.5 6.2.19 4.22.0 diff --git a/smtp-connection-pool-camel/README.md b/smtp-connection-pool-camel/README.md index 31aaeaa..8355869 100644 --- a/smtp-connection-pool-camel/README.md +++ b/smtp-connection-pool-camel/README.md @@ -43,9 +43,8 @@ to("smtppool://smtp.example.com:2525" + "&username=user&password=secret&to=recipient@example.com"); ``` -Pool tuning properties reach the pool the same way. Servers that enforce a maximum connection lifetime — Exchange -Online resets a connection after 20 minutes regardless of activity — need the age-based threshold, because a -continuously used connection never becomes idle long enough for the idle threshold to retire it: +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" @@ -53,6 +52,10 @@ to("smtppool://smtp.example.com:587" + "&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. diff --git a/smtp-connection-pool-jakarta-provider/README.md b/smtp-connection-pool-jakarta-provider/README.md index 9bd1040..c44a42b 100644 --- a/smtp-connection-pool-jakarta-provider/README.md +++ b/smtp-connection-pool-jakarta-provider/README.md @@ -93,10 +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 a transport was created; `0` disables age-based expiration | +| `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. diff --git a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java index 965ce97..c978b36 100644 --- a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java +++ b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java @@ -12,6 +12,7 @@ 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; @@ -24,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; @@ -444,44 +446,20 @@ 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. - *

- * {@code CombinedExpirationPolicies} is deliberately not used here: it holds its members in a {@link java.util.Set}, - * while {@code TimeoutExpirationPolicy} derives equality from {@code expiryAgeMs} alone and its subclasses add no - * equality of their own. Two different rules configured to the same number of milliseconds therefore compare equal - * and one of them is silently dropped from the set. */ - private static ExpirationPolicy expirationPolicy(final long expirationMillis, - final long expirationSinceCreationMillis) { + static ExpirationPolicy expirationPolicy(final long expirationMillis, + final long expirationSinceCreationMillis) { final ExpirationPolicy idlePolicy = new TimeoutSinceLastAllocationExpirationPolicy(expirationMillis, TimeUnit.MILLISECONDS); if (expirationSinceCreationMillis == 0L) { return idlePolicy; } - return new EitherExpirationPolicy(idlePolicy, - new TimeoutSinceCreationExpirationPolicy(expirationSinceCreationMillis, - TimeUnit.MILLISECONDS)); - } - - /** Expires a pooled object as soon as either of two independent rules considers it expired. */ - private static final class EitherExpirationPolicy implements ExpirationPolicy { - private final ExpirationPolicy first; - private final ExpirationPolicy second; - - EitherExpirationPolicy(final ExpirationPolicy first, final ExpirationPolicy second) { - this.first = first; - this.second = second; - } - - @Override - public boolean hasExpired(final PoolableObject poolableObject) { - return first.hasExpired(poolableObject) || second.hasExpired(poolableObject); - } - - @Override - public String toString() { - return "EitherExpirationPolicy(" + first + ", " + second + ")"; - } + final Set> policies = new HashSet>(); + policies.add(idlePolicy); + policies.add(new TimeoutSinceCreationExpirationPolicy(expirationSinceCreationMillis, + TimeUnit.MILLISECONDS)); + return new CombinedExpirationPolicies(policies); } private static String firstNonBlank(final String... candidates) { diff --git a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java index 10a6d42..d9651bc 100644 --- a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java +++ b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java @@ -31,7 +31,10 @@ 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 threshold in milliseconds measured since a physical transport was created; {@code 0} disables it. */ + /** + * 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. */ diff --git a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java index db63437..6719fc1 100644 --- a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java +++ b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java @@ -485,7 +485,7 @@ void poolCapacityTimesOutASecondExclusiveClaimAndRecoversAfterRelease() throws E } @Test - void ageBasedExpirationRetiresATransportThatNeverStaysIdleLongEnoughToExpire() throws Exception { + void ageBasedExpirationRetiresAnAvailableTransportBeforeTheIdleThreshold() throws Exception { session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_MILLIS, "60000"); session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "50"); sendOnce("secret"); @@ -515,20 +515,10 @@ void anUnsetAgeThresholdLeavesIdleOnlyExpirationBehaviourUnchanged() throws Exce assertEquals(1, FakeTransport.instances.get()); } - // Identical thresholds must keep both rules in force. A set-based combination cannot express that: the timeout - // policies derive equality from their millisecond value alone, so equal thresholds collapse into a single rule. @Test - void identicalIdleAndAgeThresholdsStillRetireATransport() throws Exception { - session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_MILLIS, "50"); - session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "50"); - sendOnce("secret"); - - final SmtpPoolManager manager = SmtpPoolRegistry.getOrCreate(session); - for (int attempt = 0; attempt < 200 && manager.getLiveTransportCount() > 0; attempt++) { - Thread.sleep(25L); - } - - assertEquals(0, manager.getLiveTransportCount()); + void aNegativeAgeThresholdIsRejectedWhenTheManagerIsCreated() { + session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "-1"); + assertThrows(IllegalArgumentException.class, () -> SmtpPoolRegistry.getOrCreate(session)); } @Test diff --git a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManagerExpirationTest.java b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManagerExpirationTest.java new file mode 100644 index 0000000..48ece33 --- /dev/null +++ b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManagerExpirationTest.java @@ -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 policy = SmtpPoolManager.expirationPolicy(50L, 50L); + final PoolableObject 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 policy = SmtpPoolManager.expirationPolicy(50L, 60_000L); + assertTrue(policy.hasExpired(transportAged(100L, 50L))); + } + + @Test + void neitherRuleExpiresBeforeItsThreshold() { + final ExpirationPolicy policy = SmtpPoolManager.expirationPolicy(50L, 100L); + assertFalse(policy.hasExpired(transportAged(99L, 49L))); + } + + @Test + void zeroCreationThresholdPreservesTheSingleIdlePolicy() { + final ExpirationPolicy 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 transportAged(final long creationAge, final long lastClaimAge) { + final PoolableObject transport = mock(PoolableObject.class); + final Map expiryState = new HashMap(); + when(transport.ageMs()).thenReturn(creationAge); + when(transport.allocationAgeMs()).thenReturn(lastClaimAge); + when(transport.getExpiriesMs()).thenReturn(expiryState); + return transport; + } +}