我自己写了一个快速测试:
import com.twitter.util.Function;
import com.twitter.util.Future;
import java.util.Random;
import org.junit.Test;
import scala.Tuple2;
public class FinagleFutureTest {
int counter = 0;
@Test
public void test(){
Counter counter = new Counter();
Future<Counter> one = Future.value(counter).flatMap(new IncrementFunction());
Future<Counter> two = one.flatMap(new IncrementFunction());
Future<Tuple2<Counter, Counter>> three = two.join(one);
Tuple2<Counter, Counter> tuple = three.flatMap(new TupleFunction()).get();
System.out.println("one: "+ tuple._2().count+", "+tuple._2().randomInt);
System.out.println("two: "+ tuple._1().count+", "+tuple._1().randomInt);
}
static class TupleFunction extends Function<Tuple2<Counter, Counter>, Future<Tuple2<Counter, Counter>>>{
@Override
public Future<Tuple2<Counter, Counter>> apply(Tuple2<Counter, Counter> t1) {
return Future.value(t1);
}
}
static class IncrementFunction extends Function<Counter, Future<Counter>>{
@Override
public Future<Counter> apply(Counter counter) {
counter.add();
return Future.value(counter);
}
}
static class Counter{
public int count = 0;
public int randomInt;
Counter(){
Random random = new Random();
randomInt = random.nextInt();
}
public void add(){
count++;
}
}
}
结果如下:
one: 2, 2009034289
two: 2, 2009034289
所以结论是 Future 对象无论参与多少连接操作都只会执行一次。