Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to timeout java method?

Tags:

java

I need to execute a ping webservice to check if I have connection to the endpoint and the webservice server is all fine.

It's kinda dumb but I have to call a webservice for this. The problem is that when I call the stub.ping(request) and I dont have connection it keeps trying to execute this code for like a minute... and then returns false.

Any way to make this timeout after 1 second if it cannot ping?

public boolean ping() {
        try {
            PingServiceStub stub = new PingServiceStub(soapGWEndpoint);
            ReqPing request = new ReqPing();

            UserInfo userInfo = new UserInfo();
            userInfo.setName(soapGWUser);
            userInfo.setPassword(soapGWPassword);
            ApplicationInfo applicationInfo = new ApplicationInfo();
            applicationInfo.setConfigurationName(soapGWAppName);

            stub.ping(request);

            return true;
        } catch (RemoteException | PingFault e) {
            return false;
        }
    }
like image 386
user11341081 Avatar asked Oct 15 '22 15:10

user11341081


1 Answers

You could use something like the TimeLimiter from the Google Guava library. This allows you to wrap a callable in an operation that you can call with Timeout. If the callable does not complete the operation in time, it will throw a TimeoutException which you can catch and return false after one second.

As an example:

TimeLimiter timeLimiter = new SimpleTimeLimiter();
try {
  String result = timeLimiter.callWithTimeout(
                () -> callToPing(), 1, TimeUnit.SECONDS);
  return true // Or something based on result
} catch (TimeoutException e) {
  return false
}
like image 181
Blokje5 Avatar answered Oct 19 '22 02:10

Blokje5