当前位置: 首页>>代码示例>>Java>>正文


Java Futures类代码示例

本文整理汇总了Java中io.atomix.utils.concurrent.Futures的典型用法代码示例。如果您正苦于以下问题:Java Futures类的具体用法?Java Futures怎么用?Java Futures使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Futures类属于io.atomix.utils.concurrent包,在下文中一共展示了Futures类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: openProxy

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
/**
 * Opens a new client.
 *
 * @return a future to be completed once the client has been opened
 */
private CompletableFuture<PrimitiveProxy> openProxy() {
  if (connected) {
    log.debug("Opening proxy session");

    clientFuture = new OrderedFuture<>();
    openProxy(clientFuture);

    return clientFuture.thenApply(client -> {
      synchronized (this) {
        this.log = ContextualLoggerFactory.getLogger(getClass(), LoggerContext.builder(PrimitiveProxy.class)
            .addValue(client.sessionId())
            .add("type", client.serviceType())
            .add("name", client.name())
            .build());
        this.proxy = client;
        client.addStateChangeListener(this::onStateChange);
        eventListeners.forEach(client::addEventListener);
        onStateChange(PrimitiveProxy.State.CONNECTED);
      }
      return client;
    });
  }
  return Futures.exceptionalFuture(new IllegalStateException("Client not open"));
}
 
开发者ID:atomix,项目名称:atomix,代码行数:30,代码来源:RecoveringPrimitiveProxy.java

示例2: applyCommand

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
/**
 * Applies a command entry to the state machine.
 * <p>
 * Command entries result in commands being executed on the user provided {@link PrimitiveService} and a
 * response being sent back to the client by completing the returned future. All command responses are
 * cached in the command's {@link RaftSession} for fault tolerance. In the event that the same command
 * is applied to the state machine more than once, the original response will be returned.
 * <p>
 * Command entries are written with a sequence number. The sequence number is used to ensure that
 * commands are applied to the state machine in sequential order. If a command entry has a sequence
 * number that is less than the next sequence number for the session, that indicates that it is a
 * duplicate of a command that was already applied. Otherwise, commands are assumed to have been
 * received in sequential order. The reason for this assumption is because leaders always sequence
 * commands as they're written to the log, so no sequence number will be skipped.
 */
private CompletableFuture<OperationResult> applyCommand(Indexed<CommandEntry> entry) {
  // First check to ensure that the session exists.
  RaftSession session = raft.getSessions().getSession(entry.entry().session());

  // If the session is null, return an UnknownSessionException. Commands applied to the state machine must
  // have a session. We ensure that session register/unregister entries are not compacted from the log
  // until all associated commands have been cleaned.
  if (session == null) {
    logger.warn("Unknown session: " + entry.entry().session());
    return Futures.exceptionalFuture(new RaftException.UnknownSession("unknown session: " + entry.entry().session()));
  }

  // Increment the load counter to avoid snapshotting under high load.
  raft.getLoadMonitor().recordEvent();

  // Execute the command using the state machine associated with the session.
  return session.getService()
      .executeCommand(
          entry.index(),
          entry.entry().sequenceNumber(),
          entry.entry().timestamp(),
          session,
          entry.entry().operation());
}
 
开发者ID:atomix,项目名称:atomix,代码行数:40,代码来源:RaftServiceManager.java

示例3: applyQuery

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
/**
 * Applies a query entry to the state machine.
 * <p>
 * Query entries are applied to the user {@link PrimitiveService} for read-only operations.
 * Because queries are read-only, they may only be applied on a single server in the cluster,
 * and query entries do not go through the Raft log. Thus, it is critical that measures be taken
 * to ensure clients see a consistent view of the cluster event when switching servers. To do so,
 * clients provide a sequence and version number for each query. The sequence number is the order
 * in which the query was sent by the client. Sequence numbers are shared across both commands and
 * queries. The version number indicates the last index for which the client saw a command or query
 * response. In the event that the lastApplied index of this state machine does not meet the provided
 * version number, we wait for the state machine to catch up before applying the query. This ensures
 * clients see state progress monotonically even when switching servers.
 * <p>
 * Because queries may only be applied on a single server in the cluster they cannot result in the
 * publishing of session events. Events require commands to be written to the Raft log to ensure
 * fault-tolerance and consistency across the cluster.
 */
private CompletableFuture<OperationResult> applyQuery(Indexed<QueryEntry> entry) {
  RaftSession session = raft.getSessions().getSession(entry.entry().session());

  // If the session is null then that indicates that the session already timed out or it never existed.
  // Return with an UnknownSessionException.
  if (session == null) {
    logger.warn("Unknown session: " + entry.entry().session());
    return Futures.exceptionalFuture(new RaftException.UnknownSession("unknown session " + entry.entry().session()));
  }

  // Execute the query using the state machine associated with the session.
  return session.getService()
      .executeQuery(
          entry.index(),
          entry.entry().sequenceNumber(),
          entry.entry().timestamp(),
          session,
          entry.entry().operation());
}
 
开发者ID:atomix,项目名称:atomix,代码行数:38,代码来源:RaftServiceManager.java

示例4: shutdown

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
/**
 * Shuts down the server without leaving the Raft cluster.
 *
 * @return A completable future to be completed once the server has been shutdown.
 */
public CompletableFuture<Void> shutdown() {
  if (!started) {
    return Futures.exceptionalFuture(new IllegalStateException("context not open"));
  }

  CompletableFuture<Void> future = new CompletableFuture<>();
  context.getThreadContext().execute(() -> {
    started = false;
    context.transition(Role.INACTIVE);
    future.complete(null);
  });

  return future.whenCompleteAsync((result, error) -> {
    context.close();
    started = false;
  });
}
 
开发者ID:atomix,项目名称:atomix,代码行数:23,代码来源:DefaultRaftServer.java

示例5: forward

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
/**
 * Forwards the given request to the leader if possible.
 */
protected <T extends RaftRequest, U extends RaftResponse> CompletableFuture<U> forward(T request, BiFunction<NodeId, T, CompletableFuture<U>> function) {
  CompletableFuture<U> future = new CompletableFuture<>();
  DefaultRaftMember leader = raft.getLeader();
  if (leader == null) {
    return Futures.exceptionalFuture(new RaftException.NoLeader("No leader found"));
  }

  function.apply(leader.nodeId(), request).whenCompleteAsync((response, error) -> {
    if (error == null) {
      future.complete(response);
    } else {
      future.completeExceptionally(error);
    }
  }, raft.getThreadContext());
  return future;
}
 
开发者ID:atomix,项目名称:atomix,代码行数:20,代码来源:AbstractRole.java

示例6: set

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public CompletableFuture<Versioned<byte[]>> set(DocumentPath path, byte[] value) {
  return proxy.<Update, DocumentTreeResult<Versioned<byte[]>>>invoke(UPDATE,
      SERIALIZER::encode,
      new Update(checkNotNull(path), Optional.ofNullable(value), Match.any(), Match.any()),
      SERIALIZER::decode)
      .thenCompose(result -> {
        if (result.status() == INVALID_PATH) {
          return Futures.exceptionalFuture(new NoSuchDocumentPathException());
        } else if (result.status() == ILLEGAL_MODIFICATION) {
          return Futures.exceptionalFuture(new IllegalDocumentModificationException());
        } else {
          return CompletableFuture.completedFuture(result);
        }
      }).thenApply(result -> result.result());
}
 
开发者ID:atomix,项目名称:atomix,代码行数:17,代码来源:DocumentTreeProxy.java

示例7: buildAsync

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<LeaderElector<T>> buildAsync() {
  PrimitiveProtocol protocol = protocol();
  PartitionGroup partitions = managementService.getPartitionService().getPartitionGroup(protocol);

  Map<PartitionId, CompletableFuture<AsyncLeaderElector<T>>> electors = Maps.newConcurrentMap();
  for (Partition partition : partitions.getPartitions()) {
    electors.put(partition.id(),
        newLeaderElector(partition.getPrimitiveClient().newProxy(name(), primitiveType(), protocol)));
  }

  Partitioner<String> partitioner = topic -> partitions.getPartition(topic).id();
  return Futures.allOf(new ArrayList<>(electors.values()))
      .thenApply(e -> new PartitionedAsyncLeaderElector<T>(name(), Maps.transformValues(electors, v -> v.getNow(null)), partitioner).sync());
}
 
开发者ID:atomix,项目名称:atomix,代码行数:17,代码来源:LeaderElectorProxyBuilder.java

示例8: unicast

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public <M> CompletableFuture<Void> unicast(
    String subject,
    M message,
    Function<M, byte[]> encoder,
    NodeId toNodeId) {
  try {
    byte[] payload = new ClusterMessage(
        localNodeId,
        subject,
        encoder.apply(message)
    ).getBytes();
    return doUnicast(subject, payload, toNodeId);
  } catch (Exception e) {
    return Futures.exceptionalFuture(e);
  }
}
 
开发者ID:atomix,项目名称:atomix,代码行数:18,代码来源:DefaultClusterMessagingService.java

示例9: getChildren

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public CompletableFuture<Map<String, Versioned<byte[]>>> getChildren(DocumentPath path) {
  return proxy.<GetChildren, DocumentTreeResult<Map<String, Versioned<byte[]>>>>invoke(
      GET_CHILDREN,
      SERIALIZER::encode,
      new GetChildren(checkNotNull(path)),
      SERIALIZER::decode)
      .thenCompose(result -> {
        if (result.status() == INVALID_PATH) {
          return Futures.exceptionalFuture(new NoSuchDocumentPathException());
        } else if (result.status() == ILLEGAL_MODIFICATION) {
          return Futures.exceptionalFuture(new IllegalDocumentModificationException());
        } else {
          return CompletableFuture.completedFuture(result);
        }
      }).thenApply(result -> result.result());
}
 
开发者ID:atomix,项目名称:atomix,代码行数:18,代码来源:DocumentTreeProxy.java

示例10: prepare

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public CompletableFuture<Boolean> prepare(TransactionLog<MapUpdate<K, V>> transactionLog) {
  Map<AsyncConsistentMap<K, V>, List<MapUpdate<K, V>>> updatesGroupedByMap = Maps.newIdentityHashMap();
  transactionLog.records().forEach(update -> {
    AsyncConsistentMap<K, V> map = getMap(update.key());
    updatesGroupedByMap.computeIfAbsent(map, k -> Lists.newLinkedList()).add(update);
  });
  Map<AsyncConsistentMap<K, V>, TransactionLog<MapUpdate<K, V>>> transactionsByMap =
      Maps.transformValues(updatesGroupedByMap,
          list -> new TransactionLog<>(transactionLog.transactionId(), transactionLog.version(), list));

  return Futures.allOf(transactionsByMap.entrySet()
      .stream()
      .map(e -> e.getKey().prepare(e.getValue()))
      .collect(Collectors.toList()))
      .thenApply(list -> list.stream().reduce(Boolean::logicalAnd).orElse(true));
}
 
开发者ID:atomix,项目名称:atomix,代码行数:18,代码来源:PartitionedAsyncConsistentMap.java

示例11: removeNode

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public CompletableFuture<Versioned<byte[]>> removeNode(DocumentPath path) {
  if (path.equals(DocumentPath.from("root"))) {
    return Futures.exceptionalFuture(new IllegalDocumentModificationException());
  }
  return proxy.<Update, DocumentTreeResult<Versioned<byte[]>>>invoke(UPDATE,
      SERIALIZER::encode,
      new Update(checkNotNull(path), null, Match.any(), Match.ifNotNull()),
      SERIALIZER::decode)
      .thenCompose(result -> {
        if (result.status() == INVALID_PATH) {
          return Futures.exceptionalFuture(new NoSuchDocumentPathException());
        } else if (result.status() == ILLEGAL_MODIFICATION) {
          return Futures.exceptionalFuture(new IllegalDocumentModificationException());
        } else {
          return CompletableFuture.completedFuture(result);
        }
      }).thenApply(result -> result.result());
}
 
开发者ID:atomix,项目名称:atomix,代码行数:20,代码来源:DocumentTreeProxy.java

示例12: removeAllMatching

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public void removeAllMatching(Predicate<V> p, Handler<AsyncResult<Void>> handler) {
  map.entries().thenCompose(entries -> Futures.allOf(entries.stream()
      .filter(e -> p.test(e.getValue()))
      .map(e -> map.remove(e.getKey(), e.getValue()))
      .collect(Collectors.toList())))
      .whenComplete(VertxFutures.voidHandler(handler, vertx.getOrCreateContext()));
}
 
开发者ID:atomix,项目名称:atomix-vertx,代码行数:9,代码来源:AtomixAsyncMultiMap.java

示例13: execute

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public CompletableFuture<byte[]> execute(PrimitiveOperation operation) {
  if (getState() == PrimitiveProxy.State.CLOSED) {
    return Futures.exceptionalFuture(new PrimitiveException.Unavailable());
  }
  CompletableFuture<byte[]> future = new CompletableFuture<>();
  execute(operation, 1, future);
  return future;
}
 
开发者ID:atomix,项目名称:atomix,代码行数:10,代码来源:RetryingPrimitiveProxy.java

示例14: execute

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
@Override
public CompletableFuture<ExecuteResponse> execute(ExecuteRequest request) {
  logRequest(request);
  if (request.operation().id().type() == OperationType.COMMAND) {
    return executeCommand(request).thenApply(this::logResponse);
  } else if (request.operation().id().type() == OperationType.QUERY) {
    return executeQuery(request).thenApply(this::logResponse);
  }
  return Futures.exceptionalFuture(new IllegalArgumentException("Unknown operation type"));
}
 
开发者ID:atomix,项目名称:atomix,代码行数:11,代码来源:PrimaryRole.java

示例15: getServer

import io.atomix.utils.concurrent.Futures; //导入依赖的package包/类
private CompletableFuture<TestPrimaryBackupServerProtocol> getServer(NodeId memberId) {
  TestPrimaryBackupServerProtocol server = server(memberId);
  if (server != null) {
    return Futures.completedFuture(server);
  } else {
    return Futures.exceptionalFuture(new ConnectException());
  }
}
 
开发者ID:atomix,项目名称:atomix,代码行数:9,代码来源:TestPrimaryBackupClientProtocol.java


注:本文中的io.atomix.utils.concurrent.Futures类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。