Advertisement
roman_gemini

Java 8: Asynchronous Function

Nov 4th, 2014
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. package util;
  2.  
  3. import java.util.function.Supplier;
  4.  
  5. /**
  6.  * Created by Roman on 04.11.14.
  7.  */
  8. public class AsyncFunction<T> {
  9.  
  10.     private Thread thread;
  11.     private T result;
  12.     private boolean isStarted = false;
  13.  
  14.     public AsyncFunction(Supplier<T> supplier) {
  15.         this(supplier, true);
  16.     }
  17.  
  18.     public AsyncFunction(Supplier<T> supplier, boolean autoStart) {
  19.         thread = new Thread(() -> result = supplier.get());
  20.         if (autoStart) {
  21.             thread.start();
  22.             isStarted = true;
  23.         }
  24.     }
  25.  
  26.     public void start() {
  27.         if (!isStarted) {
  28.             thread.start();
  29.         } else {
  30.             throw new RuntimeException("Thread already started");
  31.         }
  32.     }
  33.  
  34.     public T getResult() {
  35.         if (!isStarted) {
  36.             throw new RuntimeException("Thread not started");
  37.         }
  38.         try {
  39.             thread.join();
  40.             thread = null;
  41.             return result;
  42.         } catch (InterruptedException e) {
  43.             throw new RuntimeException("Interrupted by InterruptedException", e);
  44.         }
  45.     }
  46.  
  47.     public static<T> AsyncFunction<T> start(Supplier<T> supplier) {
  48.         return new AsyncFunction<>(supplier, true);
  49.     }
  50.  
  51.     public static<T> AsyncFunction<T> wait(Supplier<T> supplier) {
  52.         return new AsyncFunction<>(supplier, false);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement