Timeout a Java Method

When you run a long lasting method, you may want to set a timeout for the operation. In this example, a long lasting method called someMethod() is being wrapped within another method called someMethodWithTimeout() which will timeout in 10 seconds if someMethod() did not finish work for whatever reason.

public void someMethod() {
    // Do some long lasting work...
}
 
public void someMethodWithTimeout() {
	ExecutorService exe = Executors.newFixedThreadPool(1);
	Future<?> f = exe.submit(new Runnable() {
 
		@Override
		public void run() {
			someMethod();
		}
	});
 
	try {
		f.get(10, TimeUnit.SECONDS); // Timeout in 10 seconds.
	}catch(Exception e){
		f.cancel(true); // Stop the work
		String err = "Method timed out.";
		logger.warning(err); // Log time out
                // Some cleanup work
	}
}
This entry was posted in java and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.