-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added utility to execute functions within timeout
- Loading branch information
1 parent
47ff314
commit 6256638
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
25 changes: 25 additions & 0 deletions
25
src/main/java/io/github/pixee/security/ExecuteWithTimeout.java
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package io.github.pixee.security; | ||
|
||
import java.util.concurrent.Callable; | ||
import java.util.concurrent.Executors; | ||
import java.util.concurrent.Future; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
/** | ||
* Holds utilities for executing methods and functions within a timeout. | ||
*/ | ||
public class ExecuteWithTimeout{ | ||
|
||
|
||
/** | ||
* Tries to execute a given {@link Callable} within a given timeout in milliseconds. Returns the result if successful, otherwise throws a {@link RuntimeException}. | ||
*/ | ||
public <E> E executeWithTimeout(final Callable<E> action, final int timeout) { | ||
Future<E> maybeResult = Executors.newSingleThreadExecutor().submit(action); | ||
try { | ||
return maybeResult.get(timeout, TimeUnit.MILLISECONDS); | ||
} catch (Exception e) { | ||
throw new RuntimeException("Failed to execute within time limit."); | ||
} | ||
} | ||
} |