3

Here is what I am trying to do:

String amt = Web3j.build(new HttpService("https://ropsten.infura.io/v3/123blahblah"))
.ethGetBalance("0xblahblah", DefaultBlockParameterName.LATEST)
.send().getBalance().toString();

System.out.println(amt);

It prints the balance in wei nicely. However, the Web3 does not close and the application simply hangs. I am afraid that this would be a memory overflow if not managed properly and if too many calls are made. Also, this could lead to a potential security issue on the backend. So, the question is, how do I close the web3 as soon as I get the balance data I need ?

I've tried web3.shutdown() but it doesn't do anything.

Edit: I've noticed that there is a timeout and that it closes after several minutes. Still, I need to close it immediately after getting the data.

Edit2: This is obviously due to OkHttpClient. Related question/answer https://stackoverflow.com/questions/29055724/okhttpclient-close-connection

1 Answer 1

3

Yeah, alright, I got it. Here is the code if anyone else needs it:

import okhttp3.OkHttpClient;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.http.HttpService;

import java.io.IOException;

public class testBalance3 {

    public static void main(String[] args) throws IOException {

        okhttp3.OkHttpClient httpClient = new OkHttpClient();
        Web3j web3 = Web3j.build(new HttpService("https://ropsten.infura.io/v3/123blahkeyblahblah", httpClient));
        String amt = web3.ethGetBalance("0xblablahbla", DefaultBlockParameterName.LATEST).send().getBalance().toString();
        System.out.println(amt);
        httpClient.connectionPool().evictAll();

    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.