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