Advertisement
1gravity

Untitled

Mar 14th, 2016
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.72 KB | None | 0 0
  1. import java.util.concurrent.atomic.AtomicReference;
  2.  
  3. public abstract class AsyncRunnable<T> {
  4.     /**
  5.      * Starts executing the asynchronous code.
  6.      *
  7.      * Important: the method MUST call finish(AtomicReference<T>, T) once it's done executing
  8.      * or the thread will be blocked forever.
  9.      *
  10.      * @param notifier use this parameter to call finish(AtomicReference<T>, T).
  11.      */
  12.     protected abstract void run(AtomicReference<T> notifier);
  13.  
  14.     /**
  15.      * Call this method from the run method once it's done executing.
  16.      *
  17.      * @param notifier the same notifier variable passed into run(AtomicReference<T>).
  18.      * @param result the method's return value. MUSTN'T be null or the thread won't unblock.
  19.      */
  20.     protected final void finish(AtomicReference<T> notifier, T result) {
  21.         synchronized (notifier) {
  22.             notifier.set(result);
  23.             notifier.notify();
  24.         }
  25.     }
  26.  
  27.     /**
  28.      * Use this method to block a synchronous call when running asynchronous code.
  29.      *
  30.      * @param runnable The AsyncRunnable<T> to run.
  31.      * @param <T> The type parameter that defines the method's return type.
  32.      */
  33.     public static <T> T wait(AsyncRunnable<T> runnable) {
  34.         final AtomicReference<T> notifier = new AtomicReference<>();
  35.  
  36.         // run the asynchronous code
  37.         runnable.run(notifier);
  38.  
  39.         // wait for the asynchronous code to finish
  40.         synchronized (notifier) {
  41.             while (notifier.get() == null) {
  42.                 try {
  43.                     notifier.wait();
  44.                 } catch (InterruptedException ignore) {}
  45.             }
  46.         }
  47.  
  48.         // return the result of the asynchronous code
  49.         return notifier.get();
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement