Advertisement
Guest User

Untitled

a guest
May 21st, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. package ru.sberbank;
  2.  
  3. import java.util.concurrent.Callable;
  4.  
  5.  
  6. public class Task<T> {
  7.  
  8.   private final Callable<? extends T> callable;
  9.   private volatile RuntimeException taskException;
  10.   private volatile T result;
  11.  
  12.   public Task(Callable<? extends T> callable) {
  13.     this.callable = callable;
  14.   }
  15.  
  16.   public T get() {
  17.     T probableResult = checkResult();
  18.  
  19.     if (probableResult == null) {
  20.       synchronized (this) {
  21.         probableResult = checkResult();
  22.  
  23.         if (probableResult == null) {
  24.           try {
  25.             result = callable.call();
  26.           } catch (Exception e) {
  27.             taskException = new RuntimeException("Exception in callable.call()");
  28.             throw taskException;
  29.           }
  30.         }
  31.  
  32.       }
  33.     }
  34.  
  35.     return result;
  36.   }
  37.  
  38.   private T checkResult() {
  39.     if (result != null) {
  40.       return result;
  41.     }
  42.  
  43.     if (taskException != null) {
  44.       throw taskException;
  45.     }
  46.  
  47.     return null;
  48.   }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement