
com.groupbyinc.common.util.ThreadUtils Maven / Gradle / Ivy
package com.groupbyinc.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.ThreadFactory;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Thread utilities
*
* @author Alan Czajkowski
*/
public final class ThreadUtils {
private static final transient Logger LOG = LoggerFactory.getLogger(ThreadUtils.class);
private static final int MAX_PARALLELISM = Math.max(
1, Runtime.getRuntime()
.availableProcessors() - 1);
private ThreadUtils() {
// not publicly instantiable
}
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ie) {
LOG.warn(ie.getMessage(), ie);
}
}
public static ThreadFactory defaultThreadFactory(String name) {
return defaultThreadFactory(name, false);
}
public static ThreadFactory defaultThreadFactory(String name, boolean includeThreadNumber) {
return new DefaultThreadFactory(name, includeThreadNumber);
}
public static ForkJoinPool newForkJoinPool(String name, boolean includeThreadName) {
return newForkJoinPool(MAX_PARALLELISM, name, includeThreadName);
}
public static ForkJoinPool newForkJoinPool(int parallelism, String name, boolean includeThreadName) {
ForkJoinPool.ForkJoinWorkerThreadFactory factory = new DefaultForkJoinWorkerThreadFactory(Thread.currentThread()
.getName(), name, includeThreadName);
return new ForkJoinPool(Math.max(1, parallelism), factory, null, false);
}
public static void async(ForkJoinPool workers, Runnable runnable, Function errorMessage) {
async(workers, runnable, null, errorMessage);
}
public static void async(
ForkJoinPool workers, Runnable runnable, Supplier successMessage, Function errorMessage) {
ForkJoinTask> task = workers.submit(runnable);
try {
task.get();
if (successMessage != null) {
LOG.info("{}", successMessage.get());
}
} catch (InterruptedException | ExecutionException e) {
LOG.error(errorMessage.apply(e), e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy