Skip to content

Commit 009a25b

Browse files
steffenboeshashankiitbhu
authored andcommitted
Web3j implements AutoClosable Interface (LFDT-web3j#2102)
Signed-off-by: Steffen Börner <[email protected]> Signed-off-by: Shashank Kumar <[email protected]>
1 parent 045db98 commit 009a25b

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

core/src/main/java/org/web3j/protocol/Web3j.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import org.web3j.protocol.rx.Web3jRx;
2222

2323
/** JSON-RPC Request object building factory. */
24-
public interface Web3j extends Ethereum, Web3jRx, Batcher, BlobFee {
24+
public interface Web3j extends Ethereum, Web3jRx, Batcher, BlobFee, AutoCloseable {
2525

2626
/**
2727
* Construct a new Web3j instance.

core/src/main/java/org/web3j/protocol/core/JsonRpc2_0Web3j.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -906,4 +906,9 @@ private static BigInteger fakeExponential(BigInteger numerator) {
906906
}
907907
return output.divide(BLOB_BASE_FEE_UPDATE_FRACTION);
908908
}
909+
910+
@Override
911+
public void close() throws Exception {
912+
this.shutdown();
913+
}
909914
}

core/src/test/java/org/web3j/protocol/core/JsonRpc2_0Web3jTest.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@ public class JsonRpc2_0Web3jTest {
3737
public void testStopExecutorOnShutdown() throws Exception {
3838
web3j.shutdown();
3939

40-
verify(scheduledExecutorService).shutdown();
41-
verify(service).close();
40+
verifyServicesClosed();
4241
}
4342

4443
@Test
@@ -52,4 +51,15 @@ public void testExceptionOnServiceClosure() throws Exception {
5251
web3j.shutdown();
5352
});
5453
}
54+
55+
@Test
56+
public void shouldShutdownOnAutoClose() throws Exception {
57+
try (Web3j web3j = Web3j.build(service, 10, scheduledExecutorService)) {}
58+
verifyServicesClosed();
59+
}
60+
61+
private void verifyServicesClosed() throws IOException {
62+
verify(scheduledExecutorService).shutdown();
63+
verify(service).close();
64+
}
5565
}

0 commit comments

Comments
 (0)