io.trane.future.Future类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(9.4k)|赞(0)|评价(0)|浏览(97)

本文整理了Java中io.trane.future.Future类的一些代码示例,展示了Future类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Future类的具体详情如下:
包路径:io.trane.future.Future
类名称:Future

Future介绍

[英]Future is an abstraction to deal with asynchronicity without having to use callbacks directly or blocking threads. The primary usage for Futures on the JVM is to perform IO operations, which are asynchronous by nature. Although most IO APIs return synchronously, they do that by blocking the current Thread. For instance, the thread issues a request to a remote system and then waits until a response comes back. Considering that the JVM uses native threads, it is wasteful to block them since it leads to potential thread starvation and higher garbage collection pressure. It is hard to scale a JVM system vertically if the IO throughput is bounded by the number of threads. From the user perspective, a Future can be in three states: 1. Uncompleted 2. Completed with a value 3. Completed with an exception Instead of exposing this state to the user, Future provides combinators to express computations that run once the Future completes. The results of these combinators are Future instances that can be used to perform other transformations, giving the user a powerful tool to express complex chains of asynchronous transformations. Let's say that we need to call a remote service to get the username given an id: java Future user = userService.get(userId); It's possible to apply the map transformation that produces a Future for the username string: java Future username = user.map(user -> user.username); Note that we are using a lambda expression (user -> user.username) that takes a user and returns its username. Let's say that now we need to call a service to validate the username string. This is the result if we use the map combinator for it: java Future> isValid = username.map(username -> usernameService.isValid(username)); Given that the lambda expression calls another service and returns a Future, the produced result is a nested future (Future>). One alternative to flatten this nested result is using Future.flatten: java Future isValidFlat = Future.flatten(isValid); There's a convenient combinator called flatMap that applies both map and Future.flatten at once: java Future isValid = username.flatMap(username -> usernameService.isValid(username)); The flatMap combinator is very flexible and comes from the monad abstraction. Although useful, learning monads and category theory is not a requirement to use Futures. Strictly speaking, Future isn't a monad since it uses eager evaluation and thus breaks referential transparency. Once a Future is created, it is already running. See the "Execution Model" section for more information. There are many other useful operators to deal with exceptions, collections of futures, and others.
[中]Future是一种处理异步性的抽象,无需直接使用回调或阻塞线程。JVM上“Futures”的主要用途是执行IO操作,本质上是异步的。尽管大多数IO API是同步返回的,但它们是通过阻塞当前的“线程”来实现的。例如,线程向远程系统发出请求,然后等待响应返回。考虑到JVM使用本机线程,阻止它们是浪费的,因为这会导致潜在的线程不足和更高的垃圾收集压力。如果IO吞吐量受线程数的限制,则很难垂直扩展JVM系统。从用户的角度来看,“未来”可以有三种状态:1。未完成的2。以值3完成。“Future”在异常情况下完成,而不是向用户公开此状态,它提供组合符来表示“Future”完成后运行的计算。这些组合器的结果是“未来”实例,可用于执行其他转换,为用户提供了一个强大的工具来表达复杂的异步转换链。假设我们需要调用一个远程服务来获取给定id的用户名:java Future user=userService。获取(用户ID);`可以应用“map”转换,为用户名字符串生成“Future”:“java Future username=user。映射(用户->用户.用户名);`注意,我们使用的是一个lambda表达式(`user->user.username`),它接受一个用户并返回其用户名。假设现在我们需要调用一个服务来验证用户名字符串。如果我们对其使用'map'组合符,java Future>isValid=username,则结果就是这样。映射(用户名->用户名服务.isValid(用户名));假设lambda表达式调用另一个服务并返回一个'Future',则生成的结果是一个嵌套的Future('Future>)。展平此嵌套结果的另一种方法是使用“Future”。展平:`` java Future isValidFlat=Future。展平(有效);有一个叫做“flatMap”的方便的组合词,它同时应用“map”和“Future”。立即展平:``` java Future isValid=username。flatMap(用户名->用户名服务.isValid(用户名));“flatMap”组合器非常灵活,来自monad抽象。虽然有用,但学习单子和范畴理论并不是使用“Future”的必要条件。严格地说,“Future”不是单子,因为它使用热切的评价,因此破坏了引用的透明度。一旦“未来”被创建,它就已经在运行了。有关更多信息,请参阅“执行模型”部分。还有许多其他有用的操作符来处理异常、期货集合等。

代码示例

代码示例来源:origin: traneio/future

@Benchmark
public String mapConstN() throws CheckedFutureException {
 Future<String> f = constFuture;
 for (int i = 0; i < N.n; i++)
  f = f.map(mapF);
 return f.get(Duration.ofMillis(Long.MAX_VALUE));
}

代码示例来源:origin: traneio/ndbc

default public Exchange<T> onFailure(final Function<Throwable, Exchange<?>> e) {
 return channel -> run(channel).rescue(ex -> e.apply(ex).run(channel).flatMap(v -> Future.exception(ex)));
}

代码示例来源:origin: traneio/ndbc

protected final <T> CompletionStage<T> conv(final Future<T> fut) {
 final CompletableFuture<T> cf = new CompletableFuture<>();
 fut.onSuccess(cf::complete).onFailure(cf::completeExceptionally);
 return cf;
}

代码示例来源:origin: traneio/ndbc

static <R> Exchange<R> fail(final Throwable ex) {
 final Future<Void> result = Future.exception(ex);
 return channel -> result.unsafeCast();
}

代码示例来源:origin: traneio/future

private Future<Integer> loop(int i) {
 return Tailrec.apply(() -> {
  if (i > 0)
   return Future.value(i - 1).flatMap(this::loop);
  else
   return Future.value(0);
 });
}

代码示例来源:origin: traneio/ndbc

default public Exchange<T> onSuccess(final Function<T, Exchange<?>> f) {
 return channel -> run(channel).flatMap(v -> f.apply(v).run(channel).map(ign -> v));
}

代码示例来源:origin: traneio/future

/**
 * Selects the index of the first satisfied future.
 *
 * @param list  the list of futures to select from
 * @return      a future with the index of the first satisfied future of the list.
 */
public static <T> Future<Integer> selectIndex(final List<Future<T>> list) {
 switch (list.size()) {
 case 0:
  return Future.exception(new IllegalArgumentException("Can't select from empty list."));
 case 1:
  return list.get(0).map(v -> 0);
 default:
  final Promise<Integer> p = Promise.apply(list);
  int i = 0;
  for (final Future<?> f : list) {
   if (f instanceof SatisfiedFuture)
    return Future.value(i);
   final int ii = i;
   f.ensure(() -> p.becomeIfEmpty(Future.value(ii)));
   i++;
  }
  return p;
 }
}

代码示例来源:origin: traneio/future

@Override
 final Future<R> apply(final Future<T> result) {
  return result.map(f);
 }
}

代码示例来源:origin: traneio/future

@Override
 final Future<R> apply(final Future<T> result) {
  return result.flatMap(f);
 }
}

代码示例来源:origin: traneio/ndbc

private final Future<Void> validateN(final int n) {
 if (n >= 0) {
  final T item = items.poll();
  if (item == null)
   return Future.VOID;
  else
   return item.isValid().rescue(e -> Future.FALSE).flatMap(valid -> {
    if (!valid)
     return item.close().rescue(e -> Future.VOID).ensure(() -> sizeSemaphore.release());
    else {
     items.offer(item);
     return Future.VOID;
    }
   }).flatMap(v -> validateN(n - 1));
 } else
  return Future.VOID;
}

代码示例来源:origin: traneio/ndbc

@Override
public final Future<Boolean> isValid() {
 return query(isValidQuery).map(r -> true).rescue(e -> Future.FALSE);
}

代码示例来源:origin: traneio/future

@Benchmark
public String flatMapConstN() throws CheckedFutureException {
 Future<String> f = constFuture;
 for (int i = 0; i < N.n; i++)
  f = f.flatMap(flatMapF);
 return f.get(Duration.ofMillis(Long.MAX_VALUE));
}

代码示例来源:origin: traneio/ndbc

@Override
public final <T> Future<T> transactional(final Supplier<Future<T>> supplier) {
  if (currentTransaction.get().isPresent())
    return Future.flatApply(supplier);
  else
    return pool.acquire().flatMap(c -> {
      currentTransaction.set(Optional.of(c));
      return c.beginTransaction().flatMap(v -> supplier.get()).transformWith(new Transformer<T, Future<T>>() {
        @Override
        public Future<T> onException(final Throwable ex) {
          currentTransaction.set(Optional.empty());
          return c.rollback().flatMap(v -> Future.exception(ex));
        }
        @Override
        public Future<T> onValue(final T value) {
          currentTransaction.set(Optional.empty());
          return c.commit().map(v -> value);
        }
      }).ensure(() -> pool.release(c));
    });
}

代码示例来源:origin: traneio/future

return emptyList();
return list.get(0).map(Arrays::asList);
return list.get(0).biMap(list.get(1), Arrays::asList);
  return f.unsafeCast();
  f.respond(responder);

代码示例来源:origin: traneio/ndbc

private final <T> InterruptHandler handler(final Promise<T> p) {
 return ex -> backendKeyData.ifPresent(data -> channelSupplier.get()
   .flatMap(channel -> Exchange
     .send(marshallers.cancelRequest, new CancelRequest(data.processId, data.secretKey))
     .then(Exchange.CLOSE).run(channel))
   .onFailure(e -> log.warn("Can't cancel request. Reason: " + e)));
}

代码示例来源:origin: traneio/ndbc

private final <T> Future<T> withConnection(final Function<Connection, Future<T>> f) {
  final Optional<Connection> transaction = currentTransaction.get();
  if (transaction.isPresent())
    return f.apply(transaction.get());
  else
    return pool.acquire().flatMap(c -> {
      return Future.flatApply(() -> f.apply(c)).ensure(() -> pool.release(c));
    });
}

代码示例来源:origin: traneio/future

@Override
public final void onException(final Throwable ex) {
 task.cancel(false);
 becomeIfEmpty(Future.exception(ex));
}

代码示例来源:origin: traneio/ndbc

@Override
public Future<T> acquire() {
 if (closed)
  return Future.exception(new RuntimeException("Pool closed"));
 else {
  final T item = items.poll();
  if (item != null)
   return Future.value(item);
  else if (sizeSemaphore.tryAcquire()) {
   final Future<T> conn = supplier.get();
   return connectionTimeout.map(t -> conn.within(t, scheduler)).orElse(conn);
  } else if (waitersSemaphore.tryAcquire()) {
   final Promise<T> p = Promise.apply();
   waiters.offer(p);
   return p;
  } else
   return Future.exception(new RuntimeException("Pool exhausted"));
 }
}

代码示例来源:origin: traneio/ndbc

private final <T> InterruptHandler handler(final Promise<T> p) {
 return ex -> {
  final DataSource<PreparedStatement, Row> ds = dataSourceSupplier.get();
  ds.execute("KILL QUERY " + connectionId)
    .onFailure(e -> log.warn("Can't cancel request. Reason: " + e))
    .ensure(() -> ds.close());
 };
}

代码示例来源:origin: traneio/ndbc

private final <T> Future<T> execute(final Exchange<T> exchange) {
 try {
  final Future<T> run = exchange.run(channel);
  return queryTimeout.map(t -> run.within(t, scheduler)).orElse(run);
 } catch (final Throwable t) {
  NonFatalException.verify(t);
  return Future.exception(t);
 }
}

相关文章