1
votes

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 ?

1
What do you mean by "timeout"? If you mean kill the operation after some period of time, you can't do that without running the operation in a separate thread. (You can, of course, embed timer checks in loops in the code, and, eg, throw an exception when the time limit is exceeded, but this requires significant "cooperation" on the part of the "suspect" code.) - Hot Licks
hi Hot Licks that is exactly what I meant, sorry for poor problem description. - Gandalf StormCrow

1 Answers

1
votes

You can have a look at TimeLimiter from that can take any class and produce time-limited proxy. But it still uses thread pool internally to wait for Future (at least the default SimpleTimeLimiter implementation).

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 Future is the only way.