1

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 ?

2
  • 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.) Commented Oct 3, 2012 at 21:42
  • hi Hot Licks that is exactly what I meant, sorry for poor problem description. Commented Oct 3, 2012 at 21:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

hi Tomasz Nurkiewicz I'm not sure why I said that I don't want it to run in the separate thread. I said this because this code is already executing as part of the runnable object in several threads and I meant not to add more complexity. But as long as it "looks" like same thread it's good enough for me, because I'm creating sequential process (which is run by many threads at the same time).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.