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

com.mageddo.tobby.internal.utils.Threads Maven / Gradle / Ivy

There is a newer version: 2.1.6-alpha
Show newest version
package com.mageddo.tobby.internal.utils;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Collectors;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Threads {

  public static ExecutorService newPool(int size) {
    return Executors.newFixedThreadPool(size, r -> {
      Thread t = Executors
          .defaultThreadFactory()
          .newThread(r);
      t.setDaemon(true);
      return t;
    });
  }

  public static  List executeAndGet(
      ExecutorService pool, List objects, Function converter
  ) {
    final List> futures = objects.stream()
        .map(it -> pool.submit(() -> converter.apply(it)))
        .collect(Collectors.toList());
    return get(futures);
  }

  /**
   * Submit all callables at the thread pool and wait all the futures to return.
   */
  public static  List executeAndGet(ExecutorService executorService, List> callables) {
    final List> futures = new ArrayList<>();
    for (Callable callable : callables) {
      futures.add(executorService.submit(callable));
    }
    return get(futures);
  }

  /**
   * Wait all the futures to return.
   */
  public static  List get(List> futures) {
    final List results = new ArrayList<>();
    for (Future future : futures) {
      try {
        results.add(future.get());
      } catch (InterruptedException e) {
        throw new UncheckedInterruptedException(e);
      } catch (ExecutionException e) {
        throw new UncheckedExecutionException(e);
      }
    }
    return results;
  }

  /**
   * Sleep for some duration.
   *
   * @throws UncheckedInterruptedException when thread is interrupted.
   */
  public static void sleep(Duration duration) {
    try {
      Thread.sleep(duration.toMillis());
    } catch (InterruptedException e) {
      throw new UncheckedInterruptedException(e);
    }
  }

  public static void threadDump(){
    Thread
        .getAllStackTraces()
        .keySet()
        .stream()
        .map(it -> String.format("%s(%s)", it.getName(), it.getState()))
        .forEach(System.out::println);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy