Last active
December 31, 2015 16:18
-
-
Save dopoljak/8012393 to your computer and use it in GitHub Desktop.
Execute task in maximum amount of time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
import java.util.concurrent.TimeUnit; | |
import java.util.concurrent.TimeoutException; | |
/** | |
* | |
* @author DoDo <[email protected]> | |
*/ | |
public class TimeoutExecutor | |
{ | |
public static Object execute(final long timeout, final TimeUnit unit, final Callable executable) throws InterruptedException, ExecutionException, TimeoutException | |
{ | |
final long start_time = System.currentTimeMillis(); | |
final ExecutorService executor = Executors.newSingleThreadExecutor(); | |
try | |
{ | |
final Future<String> future = executor.submit(new Callable() | |
{ | |
@Override | |
public Object call() throws Exception | |
{ | |
return executable.call(); | |
} | |
}); | |
return future.get(timeout, unit); | |
} | |
finally { | |
executor.shutdownNow(); | |
System.out.println("Executed in : " + (System.currentTimeMillis() - start_time)); | |
} | |
} | |
public static void main(String[] args) | |
{ | |
try | |
{ | |
final long timeoutMilis = 25; | |
final String response = (String) TimeoutExecutor.execute(timeoutMilis, TimeUnit.MILLISECONDS, new Callable() | |
{ | |
public Object call() throws Exception | |
{ | |
System.out.println("Starting operation ..."); | |
Thread.sleep(new Random().nextInt(50)); | |
System.out.println("Operation finished in time."); | |
return "Executed in time"; | |
} | |
}); | |
System.out.println("Result : " + response); | |
} | |
catch (TimeoutException ex) | |
{ | |
System.out.println("TimeoutException occured ..."); | |
} | |
catch (Exception ex) | |
{ | |
System.out.println("Exception ... "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment