Skip to content

Commit

Permalink
Added utility to execute functions within timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
andrecsilva committed Dec 17, 2024
1 parent 47ff314 commit 6256638
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/main/java/io/github/pixee/security/ExecuteWithTimeout.java
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.");
}
}
}

0 comments on commit 6256638

Please sign in to comment.