org.rajivprab.cava.ThreadUtilc Maven / Gradle / Ivy
Show all versions of cava Show documentation
package org.rajivprab.cava;
import org.rajivprab.cava.exception.CheckedExceptionWrapper;
import org.rajivprab.cava.exception.ExecutionExceptionc;
import org.rajivprab.cava.exception.InterruptedExceptionc;
import org.rajivprab.cava.exception.TimeoutExceptionc;
import java.time.Duration;
import java.util.concurrent.*;
/**
* Library that provides user-friendly Thread class access
*
* Created by rprabhakar on 12/15/15.
*/
public class ThreadUtilc {
// ---------- Sleep ------------
public static void sleep(Duration duration) {
sleep(duration.toMillis());
}
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new InterruptedExceptionc(e);
}
}
// ---------- Fork ------------
public static FutureTask fork(Runnable runnable) {
return fork(() -> { runnable.run(); return true; });
}
public static FutureTask fork(Callable callable) {
FutureTask futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
return futureTask;
}
// ---------- Get ------------
public static T call(Callable callable) {
try {
return callable.call();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new CheckedExceptionWrapper(e);
}
}
public static T get(Future future) {
return get(future, Duration.ofDays(100000));
}
public static T get(Future future, long timeoutMs) {
return get(future, Duration.ofMillis(timeoutMs));
}
// InterruptedException and TimeoutException are wrapped into their respective RuntimeException wrappers
// When encountering ExecutionException, the cause itself is thrown, with a CheckedExceptionWrapper only if needed
// The ExecutionException is logged in the log-file, if details from the parent-stack-trace are needed
public static T get(Future future, Duration duration) {
try {
return future.get(duration.toNanos(), TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
throw new InterruptedExceptionc(e);
} catch (TimeoutException e) {
throw new TimeoutExceptionc(e);
} catch (ExecutionException e) {
// Do not simply throw the cause, because that lacks the stack-trace for this get-method
// Do not wrap e.cause inside CheckedExceptionWrapper, because we would still have above problem
throw new ExecutionExceptionc(e);
}
}
}