That heavily depends on what your method is doing. The simplest approach would be to periodically check how long the method has been executing and return when the limit is exceeded.
long t0 = System.currentTimeMillis();
// do something
long t1 = System.currentTimeMillis();
if (t1-t0 > x*1000) {
return;
}
If you want to run the method in a separate thread, then you could do something like this:
public <T> T myMethod() {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
try {
T value = executor.invokeAny(Collections.singleton(new Callable<T>() {
@Override
public T call() throws Exception {
//your actual method code here
return null;
}
}), 3, TimeUnit.SECONDS);
System.out.println("All went fine");
return value;
} catch (TimeoutException e) {
System.out.println("Exceeded time limit, interrupted");
} catch (Exception e) {
System.out.println("Some error happened, handle it properly");
}
return null; /*some default value*/
} finally {
executor.shutdownNow();
}
}
Please note that if you're doing some un-interruptible IO in the thread, this method will not work..