Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to ensure an interface method doesn't take more time than X?

Tags:

java

interface

I have an interface method boolean right(), if it isn't "answering" in a second, it should return false.

like image 304
Jan Avatar asked Aug 05 '10 07:08

Jan


1 Answers

Yes, this is possible with e.g. java.util.concurrent.Future<V> (the standard interface to represents the result of an asynchronous computation of type V), combined with the method get(long timeout, TimeUnit unit). The method may throw TimeoutException, among other exceptions, but otherwise returns the computed result on normal execution.

In this case you want a Future<Boolean>, with get(1, TimeUnit.SECONDS) within a try-catch block, handling TimeOutException per your specification.

Available concrete implementations are FutureTask<V> and SwingWorker<T,V>. If this is within the context of Swing application, then you'd want to use the latter.

See also

  • Effective Java 2nd Edition, Item 68: Prefer executors and tasks to threads
  • Concurrent Programming with J2SE 5.0
  • Java Tutorials/Concurrency
  • Java Tutorials/Swing/How to use Threads - important read if you're using Swing!
like image 145
polygenelubricants Avatar answered Nov 14 '22 23:11

polygenelubricants