From 4b17df85b365f1f1e5a3b32c537a7ead4c94111d Mon Sep 17 00:00:00 2001 From: James Hilliard Date: Wed, 26 May 2021 23:10:22 -0600 Subject: [PATCH] Use monotonic clocks for MUXPool and fix timeout calculation bug. --- .../main/java/org/jpos/q2/iso/MUXPool.java | 27 ++++++++++--------- .../java/org/jpos/q2/iso/MUXPoolTest.java | 2 +- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/jpos/src/main/java/org/jpos/q2/iso/MUXPool.java b/jpos/src/main/java/org/jpos/q2/iso/MUXPool.java index f1cbde9f69..34593e4702 100644 --- a/jpos/src/main/java/org/jpos/q2/iso/MUXPool.java +++ b/jpos/src/main/java/org/jpos/q2/iso/MUXPool.java @@ -27,6 +27,7 @@ import org.jpos.util.NameRegistrar; import java.io.IOException; +import java.time.Duration; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicInteger; @@ -70,13 +71,12 @@ public void stopService () { NameRegistrar.unregister ("mux."+getName ()); } public ISOMsg request (ISOMsg m, long timeout) throws ISOException { - long maxWait = System.currentTimeMillis() + timeout; - MUX mux = getMUX(m,maxWait); + Duration maxWait = Duration.ofNanos(System.nanoTime()).plus(Duration.ofMillis(timeout)); + MUX mux = getMUX(m,timeout); if (mux != null) { - timeout = maxWait - System.currentTimeMillis(); - if (timeout >= 0) - return mux.request (m, timeout); + if (timeout > 0) + return mux.request (m, Math.max(maxWait.minus(Duration.ofNanos(System.nanoTime())).toMillis(), 1L)); } return null; } @@ -96,15 +96,19 @@ public boolean isConnected() { return false; } protected MUX firstAvailableMUX (long maxWait) { + Duration now = Duration.ofNanos(System.nanoTime()); + Duration timeout = Duration.ofMillis(maxWait).plus(now); do { for (MUX m : mux) if (isUsable(m)) return m; ISOUtil.sleep (1000); - } while (System.currentTimeMillis() < maxWait); + } while (Duration.ofNanos(System.nanoTime()).compareTo(timeout) < 0); return null; } protected MUX nextAvailableMUX (int mnumber, long maxWait) { + Duration now = Duration.ofNanos(System.nanoTime()); + Duration timeout = Duration.ofMillis(maxWait).plus(now); do { for (int i=0; i= 0) - mux.request(m, timeout,r, handBack); + if (timeout > 0) + mux.request(m, Math.max(maxWait.minus(Duration.ofNanos(System.nanoTime())).toMillis(), 1L),r, handBack); else { new Thread() { public void run() { diff --git a/jpos/src/test/java/org/jpos/q2/iso/MUXPoolTest.java b/jpos/src/test/java/org/jpos/q2/iso/MUXPoolTest.java index be456e786d..6f95724e36 100644 --- a/jpos/src/test/java/org/jpos/q2/iso/MUXPoolTest.java +++ b/jpos/src/test/java/org/jpos/q2/iso/MUXPoolTest.java @@ -93,7 +93,7 @@ public void testRequestThrowsNullPointerException() throws Throwable { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { - assertEquals("Cannot read the array length because \"\" is null", ex.getMessage(), "ex.getMessage()"); + assertEquals("Cannot read the array length because \"\" is null", ex.getMessage(), "ex.getMessage()"); } } }