I’ve looked over some existing answers here on SO and I’ve used Future in combination with ExecutorService to set timeout with TimeUnit to method.
But I’m trying to set timeout on a method inside my service implementation meaning that caller class is consuming interface.
So I’d like to avoid implementing callable in my service implementation, because I want this method to get executed in the same Thread.
Is there other way to set timeout or simulate timeout on a given method ?
You can have a look at
TimeLimiterfrom guava that can take any class and produce time-limited proxy. But it still uses thread pool internally to wait forFuture(at least the defaultSimpleTimeLimiterimplementation).I you want to run method in the same thread, you must have another thread to interrupt it after given timeout. And interruption won’t always work. Thus thread pool and
Futureis the only way.