diff --git a/core/src/main/java/org/web3j/protocol/Web3j.java b/core/src/main/java/org/web3j/protocol/Web3j.java index 64c2eaa2c..6f9c15435 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 7c8198287..0cb11eff9 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 e08633ebc..71a9915ae 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(); + } }