All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.rajivprab.cava.ThreadUtilc Maven / Gradle / Ivy

There is a newer version: 3.3.0
Show newest version
package org.rajivprab.cava;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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 { private static final Log log = LogFactory.getLog(ThreadUtilc.class); public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { throw new InterruptException(e); } } public static FutureTask fork(Callable callable) { FutureTask futureTask = new FutureTask<>(callable); Thread thread = new Thread(futureTask); thread.start(); return futureTask; } public static FutureTask fork(Runnable runnable) { return fork(() -> { runnable.run(); return true; }); } 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 InterruptException(e); } catch (TimeoutException e) { throw new TimeException(e); } catch (ExecutionException e) { log.warn("Hit ExecutionException while calling future.get", e); Throwable cause = e.getCause(); throw (cause instanceof RuntimeException) ? (RuntimeException) cause : new CheckedExceptionWrapper(cause); } } public static class ExecException extends CheckedExceptionWrapper { public ExecException(ExecutionException e) { super(e); } } public static class InterruptException extends CheckedExceptionWrapper { public InterruptException(InterruptedException e) { super(e); } } public static class TimeException extends CheckedExceptionWrapper { public TimeException(TimeoutException e) { super(e); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy