From be923f2b3a89264643670299b919a143f25a736d Mon Sep 17 00:00:00 2001 From: "ilya.kazakov" Date: Tue, 10 Nov 2026 14:41:36 +0200 Subject: [PATCH] Remove streamsupport-minifuture dependency - Replace java8 `CompletableFuture` with a package-private `CallFuture` in `Client` and `Subscription` - Remove the `streamsupport-minifuture` dependency from `build.gradle` - Remove the `README` note about excluding minifuture - Update comments that mention `orTimeout` and `CompletableFuture` - Add `CallFutureTest` - Add a changelog entry --- README.md | 8 - centrifuge/build.gradle | 1 - .../centrifugal/centrifuge/CallFuture.java | 72 +++++++++ .../github/centrifugal/centrifuge/Client.java | 49 +++---- .../centrifugal/centrifuge/Subscription.java | 19 ++- .../centrifuge/CallFutureTest.java | 137 ++++++++++++++++++ .../ConnectFailureHandlingTest.java | 2 +- .../UnsubscribeTimeoutThreadSafetyTest.java | 6 +- changelog.md | 5 + 9 files changed, 250 insertions(+), 49 deletions(-) create mode 100644 centrifuge/src/main/java/io/github/centrifugal/centrifuge/CallFuture.java create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallFutureTest.java diff --git a/README.md b/README.md index c4a4f7e..3614ac6 100644 --- a/README.md +++ b/README.md @@ -14,14 +14,6 @@ The features implemented by this SDK can be found in [SDK feature matrix](https: Library available in Maven: https://search.maven.org/artifact/io.github.centrifugal/centrifuge-java -This library depends on `streamsupport-minifuture`. In case your project has a dependency to `streamsupport-cfuture` and you have a class name conflicts, you can exclude minifuture safely. Example for Gradle: - -``` -implementation('io.github.centrifugal:centrifuge-java:{version}') { - exclude group: 'net.sourceforge.streamsupport', module: 'streamsupport-minifuture' -} -``` - ## Javadoc online http://www.javadoc.io/doc/io.github.centrifugal/centrifuge-java diff --git a/centrifuge/build.gradle b/centrifuge/build.gradle index b88a338..41cde16 100644 --- a/centrifuge/build.gradle +++ b/centrifuge/build.gradle @@ -47,7 +47,6 @@ configurations { dependencies { api 'com.squareup.okhttp3:okhttp:4.12.0' implementation 'com.google.protobuf:protobuf-javalite:3.25.5' - implementation 'net.sourceforge.streamsupport:streamsupport-minifuture:1.7.4' testImplementation 'junit:junit:4.13.2' // In-process WebSocket server for channel compaction tests (the feature is diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/CallFuture.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/CallFuture.java new file mode 100644 index 0000000..5ed0052 --- /dev/null +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/CallFuture.java @@ -0,0 +1,72 @@ +package io.github.centrifugal.centrifuge; + +/** + * The outcome of one call: completed once, with a result or with an error. A single + * listener is notified on the thread that completes the future, or at once if the + * future is already done. + */ +final class CallFuture { + + interface Consumer { + void accept(T value); + } + + interface Function { + R apply(T value); + } + + interface Listener { + void onDone(T result, Throwable error); + } + + private boolean done; + private T result; + private Throwable error; + private Listener listener; + + boolean complete(T result) { + return this.settle(result, null); + } + + boolean completeExceptionally(Throwable error) { + if (error == null) { + throw new NullPointerException(); + } + return this.settle(null, error); + } + + synchronized boolean isDone() { + return this.done; + } + + void whenComplete(Listener listener) { + synchronized (this) { + if (this.listener != null) { + throw new IllegalStateException("listener already set"); + } + if (!this.done) { + this.listener = listener; + return; + } + } + listener.onDone(this.result, this.error); + } + + private boolean settle(T result, Throwable error) { + Listener l; + synchronized (this) { + if (this.done) { + return false; + } + this.done = true; + this.result = result; + this.error = error; + l = this.listener; + this.listener = null; + } + if (l != null) { + l.onDone(result, error); + } + return true; + } +} diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index ec48d59..2469c2d 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -22,7 +22,6 @@ import io.github.centrifugal.centrifuge.internal.backoff.Backoff; import io.github.centrifugal.centrifuge.internal.protocol.Protocol; -import java8.util.concurrent.CompletableFuture; import okhttp3.Credentials; import okhttp3.Headers; import okhttp3.OkHttpClient; @@ -49,7 +48,7 @@ public class Client { private String token; private com.google.protobuf.ByteString data; private final EventListener listener; - private final Map> futures = new ConcurrentHashMap<>(); + private final Map> futures = new ConcurrentHashMap<>(); private final Map connectCommands = new ConcurrentHashMap<>(); private final Map connectAsyncCommands = new ConcurrentHashMap<>(); @@ -380,7 +379,7 @@ public boolean close(long awaitMilliseconds) throws InterruptedException { this.executor.submit(() -> { // Tear down the connection synchronously on the executor thread // so any future-cleanup tasks scheduled by processDisconnect - // (e.g. orTimeout/exceptionally re-submits) get queued before + // (e.g. re-submits from call error handlers) get queued before // we mark the executor shutdown. WebSocket last = Client.this.ws; Client.this.processDisconnect(DISCONNECTED_DISCONNECT_CALLED, "client closed", false); @@ -497,7 +496,7 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { private void failPendingCalls() { // From a copy: a failure handler may register a new call. - for (CompletableFuture f : new ArrayList<>(this.futures.values())) { + for (CallFuture f : new ArrayList<>(this.futures.values())) { f.completeExceptionally(new IOException()); } } @@ -852,8 +851,8 @@ private static long nowMs() { * handler got the timeout as a second callback, and it failed a call on * its own thread although the reply was already waiting. */ - void settle(CompletableFuture f, java8.util.function.Consumer onResult, - java8.util.function.Function onError) { + void settle(CallFuture f, CallFuture.Consumer onResult, + CallFuture.Function onError) { final long due = nowMs() + this.opts.getTimeout(); ScheduledFuture timer; try { @@ -871,8 +870,7 @@ void settle(CompletableFuture f, java8.util.function.Consumer onResult if (error == null) { onResult.accept(result); } else { - onError.apply(error instanceof java8.util.concurrent.CompletionException && error.getCause() != null - ? error.getCause() : error); + onError.apply(error); } } catch (Throwable t) { // E.g. an app callback that threw: reported, never called again. @@ -881,7 +879,7 @@ void settle(CompletableFuture f, java8.util.function.Consumer onResult }); } - private void expire(CompletableFuture f, long due) { + private void expire(CallFuture f, long due) { if (f.isDone()) { return; } @@ -983,7 +981,7 @@ private void sendSubscribeSynchronized(Subscription sub, Protocol.SubscribeReque .setSubscribe(req) .build(); - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.futures.put(cmd.getId(), f); this.settle(f, reply -> { if (Client.this.getState() != ClientState.CONNECTED) { @@ -1043,7 +1041,7 @@ private void sendUnsubscribeSynchronized(String channel) { .build(); final WebSocket unsubscribeWs = this.ws; - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.futures.put(cmd.getId(), f); this.settle(f, reply -> { this.futures.remove(cmd.getId()); @@ -1315,7 +1313,7 @@ private void handleConnectReply(Protocol.Reply reply) { Protocol.Command cmd = entry.getValue(); boolean sent = this.ws.send(ByteString.of(this.serializeCommand(cmd))); if (!sent) { - CompletableFuture f = this.futures.get(cmd.getId()); + CallFuture f = this.futures.get(cmd.getId()); if (f != null) { f.completeExceptionally(new IOException()); } @@ -1326,7 +1324,7 @@ private void handleConnectReply(Protocol.Reply reply) { for (Map.Entry entry : this.connectAsyncCommands.entrySet()) { Protocol.Command cmd = entry.getValue(); - CompletableFuture f = this.futures.get(cmd.getId()); + CallFuture f = this.futures.get(cmd.getId()); boolean sent = this.ws.send(ByteString.of(this.serializeCommand(cmd))); if (!sent) { if (f != null) { @@ -1455,7 +1453,7 @@ private void sendConnect() { .build(); final WebSocket connectWs = this.ws; - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.futures.put(cmd.getId(), f); this.settle(f, reply -> { this.futures.remove(cmd.getId()); @@ -1465,8 +1463,7 @@ private void sendConnect() { this.handleDispatchError(e); } }, e -> { - // A timeout completes the future on the CompletableFuture delay - // scheduler thread - hop to the executor like other command failures. + // Handle the failure in a separate executor task. this.executor.submit(() -> { Client.this.futures.remove(cmd.getId()); // Failed because the connection was already torn down (disconnect @@ -1490,7 +1487,7 @@ private void failUnauthorized() { private void processReply(Protocol.Reply reply) throws Exception { if (reply.getId() > 0) { - CompletableFuture cf = this.futures.get(reply.getId()); + CallFuture cf = this.futures.get(reply.getId()); if (cf != null) cf.complete(reply); } else { if (reply.hasPush()) { @@ -1702,7 +1699,7 @@ private void sendSynchronized(byte[] data, CompletionCallback cb) { .setSend(req) .build(); - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.futures.put(cmd.getId(), f); this.settle(f, reply -> { this.cleanCommandFuture(cmd); @@ -1727,7 +1724,7 @@ private void sendSynchronized(byte[] data, CompletionCallback cb) { } } - private void enqueueCommandFuture(Protocol.Command cmd, CompletableFuture f) { + private void enqueueCommandFuture(Protocol.Command cmd, CallFuture f) { this.futures.put(cmd.getId(), f); if (this.getState() != ClientState.CONNECTED) { this.connectCommands.put(cmd.getId(), cmd); @@ -1775,7 +1772,7 @@ private void rpcSynchronized(String method, byte[] data, ResultCallback f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { @@ -1820,7 +1817,7 @@ private void publishSynchronized(String channel, byte[] data, ResultCallback f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { @@ -1866,7 +1863,7 @@ private void historySynchronized(String channel, HistoryOptions opts, ResultCall .setHistory(req) .build(); - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { @@ -1914,7 +1911,7 @@ private void presenceSynchronized(String channel, ResultCallback .setPresence(req) .build(); - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { @@ -1955,7 +1952,7 @@ private void presenceStatsSynchronized(String channel, ResultCallback f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { @@ -1988,7 +1985,7 @@ private void refreshSynchronized(String token, ResultCallback f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { @@ -2019,7 +2016,7 @@ void subRefreshSynchronized(String channel, String token, ResultCallback f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index 71eaf54..8f5ca7e 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -8,7 +8,6 @@ import io.github.centrifugal.centrifuge.internal.backoff.Backoff; import io.github.centrifugal.centrifuge.internal.protocol.Protocol; -import java8.util.concurrent.CompletableFuture; public class Subscription { @@ -20,7 +19,7 @@ public class Subscription { private String epoch; final private SubscriptionEventListener listener; private volatile SubscriptionState state = SubscriptionState.UNSUBSCRIBED; - final private Map> futures = new ConcurrentHashMap<>(); + final private Map> futures = new ConcurrentHashMap<>(); private final Backoff backoff; private ScheduledFuture refreshTask; private ScheduledFuture resubscribeTask; @@ -289,8 +288,8 @@ void moveToSubscribed(Protocol.SubscribeResult result) throws Exception { this.client.handlePub(this.channel, publication); } - for(Map.Entry> entry: this.futures.entrySet()) { - CompletableFuture f = entry.getValue(); + for(Map.Entry> entry: this.futures.entrySet()) { + CallFuture f = entry.getValue(); f.complete(null); } this.futures.clear(); @@ -536,8 +535,8 @@ private void _unsubscribe(boolean sendUnsubscribe, int code, String reason) { if (sendUnsubscribe) { this.client.sendUnsubscribe(this.getChannel()); } - for(Map.Entry> entry: this.futures.entrySet()) { - CompletableFuture f = entry.getValue(); + for(Map.Entry> entry: this.futures.entrySet()) { + CallFuture f = entry.getValue(); f.complete(new SubscriptionStateError(this.getState())); } this.futures.clear(); @@ -585,7 +584,7 @@ public void publish(byte[] data, ResultCallback cb) { } private void publishSynchronized(byte[] data, ResultCallback cb) { - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); String uuid = UUID.randomUUID().toString(); this.futures.put(uuid, f); this.client.settle(f, err -> { @@ -610,7 +609,7 @@ public void history(HistoryOptions opts, ResultCallback cb) { } private void historySynchronized(HistoryOptions opts, ResultCallback cb) { - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); String uuid = UUID.randomUUID().toString(); this.futures.put(uuid, f); this.client.settle(f, err -> { @@ -635,7 +634,7 @@ public void presence(ResultCallback cb) { } private void presenceSynchronized(ResultCallback cb) { - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); String uuid = UUID.randomUUID().toString(); this.futures.put(uuid, f); this.client.settle(f, err -> { @@ -660,7 +659,7 @@ public void presenceStats(ResultCallback cb) { } private void presenceStatsSynchronized(ResultCallback cb) { - CompletableFuture f = new CompletableFuture<>(); + CallFuture f = new CallFuture<>(); String uuid = UUID.randomUUID().toString(); this.futures.put(uuid, f); this.client.settle(f, err -> { diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallFutureTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallFutureTest.java new file mode 100644 index 0000000..fb39259 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallFutureTest.java @@ -0,0 +1,137 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** A call future completes once and notifies its listener once. */ +public class CallFutureTest { + + @Test + public void testCompleteNotifiesListener() { + CallFuture f = new CallFuture<>(); + List calls = new CopyOnWriteArrayList<>(); + f.whenComplete((result, error) -> { + calls.add(result); + calls.add(error); + }); + assertFalse(f.isDone()); + assertTrue(f.complete("ok")); + assertTrue(f.isDone()); + assertEquals(2, calls.size()); + assertEquals("ok", calls.get(0)); + assertNull(calls.get(1)); + } + + @Test + public void testCompleteExceptionallyNotifiesListenerWithSameError() { + CallFuture f = new CallFuture<>(); + Throwable error = new IOException(); + List calls = new CopyOnWriteArrayList<>(); + f.whenComplete((result, e) -> { + calls.add(result); + calls.add(e); + }); + assertTrue(f.completeExceptionally(error)); + assertTrue(f.isDone()); + assertEquals(2, calls.size()); + assertNull(calls.get(0)); + assertSame(error, calls.get(1)); + } + + /** A listener added after completion is called at once, on the caller's thread. */ + @Test + public void testListenerAddedAfterCompletionIsCalledAtOnce() { + CallFuture f = new CallFuture<>(); + Throwable error = new TimeoutException(); + f.completeExceptionally(error); + List calls = new CopyOnWriteArrayList<>(); + Thread caller = Thread.currentThread(); + f.whenComplete((result, e) -> { + calls.add(e); + calls.add(Thread.currentThread()); + }); + assertEquals(2, calls.size()); + assertSame(error, calls.get(0)); + assertSame(caller, calls.get(1)); + } + + /** A listener added before completion runs on the thread that completes the future. */ + @Test + public void testListenerRunsOnCompletingThread() throws Exception { + CallFuture f = new CallFuture<>(); + List threads = new CopyOnWriteArrayList<>(); + f.whenComplete((result, error) -> threads.add(Thread.currentThread())); + Thread completer = new Thread(() -> f.complete("ok")); + completer.start(); + completer.join(5000); + assertEquals(1, threads.size()); + assertSame(completer, threads.get(0)); + } + + @Test + public void testSecondCompletionIsIgnored() { + CallFuture f = new CallFuture<>(); + AtomicInteger calls = new AtomicInteger(); + List results = new CopyOnWriteArrayList<>(); + f.whenComplete((result, error) -> { + calls.incrementAndGet(); + results.add(result); + }); + assertTrue(f.complete("first")); + assertFalse(f.complete("second")); + assertFalse(f.completeExceptionally(new IOException())); + assertEquals(1, calls.get()); + assertEquals("first", results.get(0)); + } + + /** Concurrent complete and completeExceptionally settle the future exactly once. */ + @Test + public void testConcurrentCompletionSettlesOnce() throws Exception { + for (int i = 0; i < 1000; i++) { + CallFuture f = new CallFuture<>(); + AtomicInteger calls = new AtomicInteger(); + f.whenComplete((result, error) -> calls.incrementAndGet()); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger wins = new AtomicInteger(); + Thread a = new Thread(() -> { + awaitQuietly(start); + if (f.complete("ok")) { + wins.incrementAndGet(); + } + }); + Thread b = new Thread(() -> { + awaitQuietly(start); + if (f.completeExceptionally(new IOException())) { + wins.incrementAndGet(); + } + }); + a.start(); + b.start(); + start.countDown(); + a.join(5000); + b.join(5000); + assertEquals(1, wins.get()); + assertEquals(1, calls.get()); + } + } + + private static void awaitQuietly(CountDownLatch latch) { + try { + latch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException ignored) { + } + } +} diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/ConnectFailureHandlingTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/ConnectFailureHandlingTest.java index f03e278..34afc34 100644 --- a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/ConnectFailureHandlingTest.java +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/ConnectFailureHandlingTest.java @@ -19,7 +19,7 @@ * A connect command that never gets a reply fails either by timing out or by the * connection going away. Both outcomes are handled by the connect future's * failure handler, which must run on the client executor like every other state - * transition — the timeout fires on the CompletableFuture delay scheduler thread — + * transition — the timeout fires on the client's scheduler thread — * and must not report a connect error once the client has already left CONNECTING. */ public class ConnectFailureHandlingTest { diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeTimeoutThreadSafetyTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeTimeoutThreadSafetyTest.java index 4441d52..03227e5 100644 --- a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeTimeoutThreadSafetyTest.java +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeTimeoutThreadSafetyTest.java @@ -15,9 +15,9 @@ import static org.junit.Assert.assertTrue; /** - * Regression test for the unsubscribe-timeout race: {@link java.util.concurrent.CompletableFuture#orTimeout} - * fails the pending future from a JDK-internal thread, not the client's dedicated - * single-thread executor. The {@code exceptionally} callback used to call + * Regression test for the unsubscribe-timeout race: the call timeout used to fail + * the pending future from a timer thread, not the client's dedicated + * single-thread executor. The failure callback used to call * {@code processDisconnect} directly on that thread, racing with everything else * the client does on its own executor. The fix re-submits the callback onto the * client's executor (mirroring the existing subscribe-timeout handling). diff --git a/changelog.md b/changelog.md index 148e810..711b9fd 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,8 @@ +Unreleased +========== + +* Remove the `streamsupport-minifuture` dependency (GPL-2.0 with Classpath Exception). Pending calls now use a small internal future. The public API and the supported Android versions do not change. + 0.3.1 =====