From 8fa31dde5b0786e6c2d4a6fc52f01e1090817f80 Mon Sep 17 00:00:00 2001 From: steffenboe Date: Wed, 25 Sep 2024 07:26:10 +0200 Subject: [PATCH] Web3j implements AutoClosable Interface (#2102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Steffen Börner --- core/src/main/java/org/web3j/protocol/Web3j.java | 2 +- .../org/web3j/protocol/core/JsonRpc2_0Web3j.java | 5 +++++ .../web3j/protocol/core/JsonRpc2_0Web3jTest.java | 14 ++++++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/org/web3j/protocol/Web3j.java b/core/src/main/java/org/web3j/protocol/Web3j.java index 64c2eaa2c2..6f9c154359 100644 --- a/core/src/main/java/org/web3j/protocol/Web3j.java +++ b/core/src/main/java/org/web3j/protocol/Web3j.java @@ -21,7 +21,7 @@ import org.web3j.protocol.rx.Web3jRx; /** JSON-RPC Request object building factory. */ -public interface Web3j extends Ethereum, Web3jRx, Batcher, BlobFee { +public interface Web3j extends Ethereum, Web3jRx, Batcher, BlobFee, AutoCloseable { /** * Construct a new Web3j instance. diff --git a/core/src/main/java/org/web3j/protocol/core/JsonRpc2_0Web3j.java b/core/src/main/java/org/web3j/protocol/core/JsonRpc2_0Web3j.java index 7c81982872..0cb11eff9f 100644 --- a/core/src/main/java/org/web3j/protocol/core/JsonRpc2_0Web3j.java +++ b/core/src/main/java/org/web3j/protocol/core/JsonRpc2_0Web3j.java @@ -906,4 +906,9 @@ private static BigInteger fakeExponential(BigInteger numerator) { } return output.divide(BLOB_BASE_FEE_UPDATE_FRACTION); } + + @Override + public void close() throws Exception { + this.shutdown(); + } } diff --git a/core/src/test/java/org/web3j/protocol/core/JsonRpc2_0Web3jTest.java b/core/src/test/java/org/web3j/protocol/core/JsonRpc2_0Web3jTest.java index e08633ebc4..71a9915aef 100644 --- a/core/src/test/java/org/web3j/protocol/core/JsonRpc2_0Web3jTest.java +++ b/core/src/test/java/org/web3j/protocol/core/JsonRpc2_0Web3jTest.java @@ -37,8 +37,7 @@ public class JsonRpc2_0Web3jTest { public void testStopExecutorOnShutdown() throws Exception { web3j.shutdown(); - verify(scheduledExecutorService).shutdown(); - verify(service).close(); + verifyServicesClosed(); } @Test @@ -52,4 +51,15 @@ public void testExceptionOnServiceClosure() throws Exception { web3j.shutdown(); }); } + + @Test + public void shouldShutdownOnAutoClose() throws Exception { + try (Web3j web3j = Web3j.build(service, 10, scheduledExecutorService)) {} + verifyServicesClosed(); + } + + private void verifyServicesClosed() throws IOException { + verify(scheduledExecutorService).shutdown(); + verify(service).close(); + } }