001/*
002 * Copyright (c) 2012-2018 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others
003 *
004 * This program and the accompanying materials are made available under the
005 * terms of the Eclipse Public License 2.0 which is available at
006 * http://www.eclipse.org/legal/epl-2.0.
007 *
008 * SPDX-License-Identifier: EPL-2.0
009 */
010
011package gololang.concurrent.async;
012
013/**
014 * Convenience implementation for pre-set futures.
015 */
016public final class AssignedFuture implements Future {
017
018  private AssignedFuture(Object value) {
019    this.value = value;
020  }
021
022  private final Object value;
023
024  /**
025   * Builds a new future that has been set to a value.
026   *
027   * @param value the future value.
028   * @return a new future object.
029   */
030  public static AssignedFuture setFuture(Object value) {
031    return new AssignedFuture(value);
032  }
033
034  /**
035   * Builds a new future that has failed.
036   *
037   * @param throwable the failure.
038   * @return a new future object.
039   */
040  public static AssignedFuture failedFuture(Throwable throwable) {
041    return new AssignedFuture(throwable);
042  }
043
044  @Override
045  public Object get() {
046    return value;
047  }
048
049  @Override
050  public Object blockingGet() throws InterruptedException {
051    return value;
052  }
053
054  @Override
055  public boolean isResolved() {
056    return true;
057  }
058
059  @Override
060  public boolean isFailed() {
061    return value instanceof Throwable;
062  }
063
064  @Override
065  public Future onSet(Observer observer) {
066    if (!isFailed()) {
067      observer.apply(value);
068    }
069    return this;
070  }
071
072  @Override
073  public Future onFail(Observer observer) {
074    if (isFailed()) {
075      observer.apply(value);
076    }
077    return this;
078  }
079
080  @Override
081  public String toString() {
082    return String.format("AssignedFuture{value=%s}", value);
083  }
084}