| 46 | /// @author shannah |
| 47 | /// |
| 48 | public class AsyncResource<V> extends Observable { |
| 49 | private final Object lock = new Object(); |
| 50 | private V value; |
| 51 | private Throwable error; |
| 52 | private SuccessCallback<V> successCallback; |
| 53 | private SuccessCallback<Throwable> errorCallback; |
| 54 | private boolean done; |
| 55 | private boolean cancelled; |
| 56 | |
| 57 | |
| 58 | @Async.Schedule |
| 59 | @SuppressWarnings("PMD.UnnecessaryConstructor") |
| 60 | public AsyncResource() { |
| 61 | } |
| 62 | |
| 63 | /// Returns true if the provided throwable was caused by a cancellation of an AsyncResource. |
| 64 | /// |
| 65 | /// #### Parameters |
| 66 | /// |
| 67 | /// - `t`: The exception to check for a cancellation. |
| 68 | /// |
| 69 | /// #### Returns |
| 70 | /// |
| 71 | /// True if the exception was caused by cancelling an AsyncResource. |
| 72 | /// |
| 73 | public static boolean isCancelled(Throwable t) { |
| 74 | if (t == null) { |
| 75 | return false; |
| 76 | } |
| 77 | if (t instanceof AsyncExecutionException) { |
| 78 | return ((AsyncExecutionException) t).isCancelled(); |
| 79 | } else { |
| 80 | return t.getClass() == CancellationException.class; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// Creates a single AsyncResource that will fire its ready() only when all of the provided resources |
| 85 | /// are ready. And will fire an exception if any of the provided resources fires an exception. |
| 86 | /// |
| 87 | /// #### Parameters |
| 88 | /// |
| 89 | /// - `resources`: One ore more resources to wrap. |
| 90 | /// |
| 91 | /// #### Returns |
| 92 | /// |
| 93 | /// A combined AsyncResource. |
| 94 | /// |
| 95 | public static AsyncResource<Boolean> all(AsyncResource<?>... resources) { |
| 96 | final AsyncResource<Boolean> out = new AsyncResource<Boolean>(); |
| 97 | final Set<AsyncResource> pending = new HashSet<AsyncResource>(Arrays.asList(resources)); |
| 98 | final boolean[] complete = new boolean[1]; |
| 99 | for (final AsyncResource<?> res : resources) { |
| 100 | res.ready(new SuccessCallback() { |
| 101 | @Override |
| 102 | public void onSucess(Object arg) { |
| 103 | synchronized (complete) { |
| 104 | if (complete[0]) { |
| 105 | return; |
nothing calls this directly
no outgoing calls
no test coverage detected