io.atomix.utils.concurrent.Futures Java Examples
The following examples show how to use
io.atomix.utils.concurrent.Futures.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NettyMessagingService.java From atomix with Apache License 2.0 | 6 votes |
/** * Bootstraps a server. * * @return a future to be completed once the server has been bound to all interfaces */ private CompletableFuture<Void> bootstrapServer() { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_REUSEADDR, true); b.option(ChannelOption.SO_BACKLOG, 128); b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)); b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024); b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024); b.childOption(ChannelOption.SO_KEEPALIVE, true); b.childOption(ChannelOption.TCP_NODELAY, true); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.group(serverGroup, clientGroup); b.channel(serverChannelClass); if (enableNettyTls) { try { b.childHandler(new SslServerChannelInitializer()); } catch (SSLException e) { return Futures.exceptionalFuture(e); } } else { b.childHandler(new BasicServerChannelInitializer()); } return bind(b); }
Example #2
Source File: AtomixCluster.java From atomix with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public synchronized CompletableFuture<Void> start() { if (closeFuture != null) { return Futures.exceptionalFuture(new IllegalStateException("AtomixCluster instance " + (closeFuture.isDone() ? "shutdown" : "shutting down"))); } if (openFuture != null) { return openFuture; } openFuture = startServices() .thenComposeAsync(v -> completeStartup(), threadContext); return openFuture; }
Example #3
Source File: Atomix.java From atomix with Apache License 2.0 | 6 votes |
/** * Starts the Atomix instance. * <p> * The returned future will be completed once this instance completes startup. Note that in order to complete startup, * all partitions must be able to form. For Raft partitions, that requires that a majority of the nodes in each * partition be started concurrently. * * @return a future to be completed once the instance has completed startup */ @Override public synchronized CompletableFuture<Void> start() { if (closeFuture != null) { return Futures.exceptionalFuture(new IllegalStateException("Atomix instance " + (closeFuture.isDone() ? "shutdown" : "shutting down"))); } LOGGER.info(BUILD); return super.start().thenRun(() -> { if (enableShutdownHook) { if (shutdownHook == null) { shutdownHook = new Thread(() -> super.stop().join()); Runtime.getRuntime().addShutdownHook(shutdownHook); } } }); }
Example #4
Source File: DefaultDistributedCounterBuilder.java From atomix with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<DistributedCounter> buildAsync() { PrimitiveProtocol protocol = protocol(); if (protocol instanceof GossipProtocol) { if (protocol instanceof CounterProtocol) { return managementService.getPrimitiveCache().getPrimitive(name, () -> CompletableFuture.completedFuture( new GossipDistributedCounter(name, (GossipProtocol) protocol, ((CounterProtocol) protocol) .newCounterDelegate(name, managementService)))) .thenApply(AsyncDistributedCounter::sync); } else { return Futures.exceptionalFuture(new UnsupportedOperationException("Counter is not supported by the provided gossip protocol")); } } else if (protocol instanceof ProxyProtocol) { return newProxy(AtomicCounterService.class, new ServiceConfig()) .thenCompose(proxy -> new AtomicCounterProxy(proxy, managementService.getPrimitiveRegistry()).connect()) .thenApply(DelegatingDistributedCounter::new) .thenApply(AsyncDistributedCounter::sync); } else { return Futures.exceptionalFuture(new ConfigurationException("Invalid protocol type")); } }
Example #5
Source File: PartitionedProxyIterator.java From atomix with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<Boolean> hasNext() { return iterator.hasNext() .thenCompose(hasNext -> { if (!hasNext) { if (partitions.hasNext()) { if (closed.get()) { return Futures.exceptionalFuture(new IllegalStateException("Iterator closed")); } iterator = partitions.next(); return hasNext(); } return CompletableFuture.completedFuture(false); } return CompletableFuture.completedFuture(true); }); }
Example #6
Source File: AbstractAtomicMapProxy.java From atomix with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<Boolean> prepare(TransactionLog<MapUpdate<K, byte[]>> transactionLog) { Map<PartitionId, List<MapUpdate<K, byte[]>>> updatesGroupedByMap = Maps.newIdentityHashMap(); transactionLog.records().forEach(update -> { updatesGroupedByMap.computeIfAbsent(getPartition(update.key()), k -> Lists.newLinkedList()).add(update); }); Map<PartitionId, TransactionLog<MapUpdate<K, byte[]>>> transactionsByMap = Maps.transformValues(updatesGroupedByMap, list -> new TransactionLog<>(transactionLog.transactionId(), transactionLog.version(), list)); return Futures.allOf(transactionsByMap.entrySet() .stream() .map(e -> getProxyClient().applyOn(e.getKey(), service -> service.prepare(e.getValue())) .thenApply(v -> v == PrepareResult.OK || v == PrepareResult.PARTIAL_FAILURE)) .collect(Collectors.toList())) .thenApply(list -> list.stream().reduce(Boolean::logicalAnd).orElse(true)); }
Example #7
Source File: AbstractRole.java From atomix with Apache License 2.0 | 6 votes |
/** * Forwards the given request to the leader if possible. */ protected <T extends RaftRequest, U extends RaftResponse> CompletableFuture<U> forward(T request, BiFunction<MemberId, 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.memberId(), request).whenCompleteAsync((response, error) -> { if (error == null) { future.complete(response); } else { future.completeExceptionally(error); } }, raft.getThreadContext()); return future; }
Example #8
Source File: AbstractAtomicMapProxy.java From atomix with Apache License 2.0 | 6 votes |
@Override public CompletableFuture<P> connect() { return super.connect() .thenCompose(v -> Futures.allOf(getPartitions().stream() .map(partitionId -> { ProxySession<? extends AtomicMapService<K>> partition = getProxyClient().getPartition(partitionId); return partition.connect() .thenRun(() -> { partition.addStateChangeListener(state -> { if (state == PrimitiveState.CONNECTED && isListening()) { partition.accept(service -> service.listen()); } }); partition.addStateChangeListener(this::onStateChange); }); }))) .thenApply(v -> (P) this); }
Example #9
Source File: RecoveringSessionClient.java From atomix with Apache License 2.0 | 6 votes |
/** * Sets the session state. * * @param state the session state */ private synchronized void onStateChange(PrimitiveState state) { if (this.state != state) { if (state == PrimitiveState.EXPIRED) { if (connected) { onStateChange(PrimitiveState.SUSPENDED); recover(); } else { log.debug("State changed: {}", state); this.state = state; stateChangeListeners.forEach(l -> l.accept(state)); } } else { log.debug("State changed: {}", state); this.state = state; stateChangeListeners.forEach(l -> l.accept(state)); if (state == PrimitiveState.CLOSED) { connectFuture = Futures.exceptionalFuture(new PrimitiveException.ClosedSession()); session = null; } } } }
Example #10
Source File: InactiveRole.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<MetadataResponse> onMetadata(MetadataRequest request) { logRequest(request); return Futures.completedFuture(logResponse(MetadataResponse.builder() .withStatus(Status.ERROR) .withError(RaftError.Type.UNAVAILABLE) .build())); }
Example #11
Source File: RaftSessionManager.java From atomix with Apache License 2.0 | 5 votes |
/** * Closes a session. * * @param sessionId the session identifier. * @param delete whether to delete the service * @return A completable future to be completed once the session is closed. */ public CompletableFuture<Void> closeSession(SessionId sessionId, boolean delete) { RaftSessionState state = sessions.get(sessionId.id()); if (state == null) { return Futures.exceptionalFuture(new RaftException.UnknownSession("Unknown session: " + sessionId)); } log.debug("Closing session {}", sessionId); CloseSessionRequest request = CloseSessionRequest.builder() .withSession(sessionId.id()) .withDelete(delete) .build(); CompletableFuture<Void> future = new CompletableFuture<>(); connection.closeSession(request).whenComplete((response, error) -> { sessions.remove(sessionId.id()); if (error == null) { if (response.status() == RaftResponse.Status.OK) { future.complete(null); } else { future.completeExceptionally(response.error().createException()); } } else { future.completeExceptionally(error); } }); return future; }
Example #12
Source File: TranscodingAsyncAtomicMap.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Boolean> replace(K1 key, long oldVersion, V1 newValue) { try { return backingMap.replace(keyEncoder.apply(key), oldVersion, valueEncoder.apply(newValue)); } catch (Exception e) { return Futures.exceptionalFuture(e); } }
Example #13
Source File: TestLogClientProtocol.java From atomix with Apache License 2.0 | 5 votes |
private CompletableFuture<TestLogServerProtocol> getServer(MemberId memberId) { TestLogServerProtocol server = server(memberId); if (server != null) { return Futures.completedFuture(server); } else { return Futures.exceptionalFuture(new ConnectException()); } }
Example #14
Source File: GossipDistributedValue.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Void> close() { try { value.close(); return CompletableFuture.completedFuture(null); } catch (Exception e) { return Futures.exceptionalFuture(e); } }
Example #15
Source File: RaftPartitionGroup.java From atomix with Apache License 2.0 | 5 votes |
/** * Handles a snapshot request from a peer. * * @return a future to be completed once the snapshot is complete */ private CompletableFuture<Void> handleSnapshot() { return Futures.allOf(partitions.values().stream() .map(partition -> partition.snapshot()) .collect(Collectors.toList())) .thenApply(v -> null); }
Example #16
Source File: AtomicDocumentTreeProxy.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Boolean> replace(DocumentPath path, byte[] newValue, long version) { checkPath(path); return getProxyClient().applyBy(name(), service -> service.replace(path, newValue, version)) .thenCompose(result -> { if (result.status() == DocumentTreeResult.Status.INVALID_PATH) { return Futures.exceptionalFuture(new NoSuchDocumentPathException()); } else if (result.status() == DocumentTreeResult.Status.ILLEGAL_MODIFICATION) { return Futures.exceptionalFuture(new IllegalDocumentModificationException()); } else { return CompletableFuture.completedFuture(result.status() == DocumentTreeResult.Status.OK); } }); }
Example #17
Source File: TranscodingAsyncAtomicCounterMap.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Boolean> remove(K1 key, long value) { try { return backingMap.remove(keyEncoder.apply(key), value); } catch (Exception e) { return Futures.exceptionalFuture(e); } }
Example #18
Source File: TranscodingAsyncAtomicMultimap.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Boolean> containsKey(K1 key) { try { return backingMap.containsKey(keyEncoder.apply(key)); } catch (Exception e) { return Futures.exceptionalFuture(e); } }
Example #19
Source File: LogProxySession.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Void> accept(Consumer<S> operation) { if (session.getState() == PrimitiveState.CLOSED) { return Futures.exceptionalFuture(new PrimitiveException.ClosedSession()); } return proxy.accept(operation); }
Example #20
Source File: LocalRaftServerProtocol.java From atomix with Apache License 2.0 | 5 votes |
CompletableFuture<byte[]> closeSession(byte[] request) { if (closeSessionHandler != null) { return closeSessionHandler.apply(decode(request)).thenApply(this::encode); } else { return Futures.exceptionalFuture(new ConnectException()); } }
Example #21
Source File: RaftSessionManager.java From atomix with Apache License 2.0 | 5 votes |
/** * Resets indexes for the given session. * * @param sessionId The session for which to reset indexes. * @return A completable future to be completed once the session's indexes have been reset. */ CompletableFuture<Void> resetIndexes(SessionId sessionId) { RaftSessionState sessionState = sessions.get(sessionId.id()); if (sessionState == null) { return Futures.exceptionalFuture(new IllegalArgumentException("Unknown session: " + sessionId)); } CompletableFuture<Void> future = new CompletableFuture<>(); KeepAliveRequest request = KeepAliveRequest.builder() .withSessionIds(new long[]{sessionId.id()}) .withCommandSequences(new long[]{sessionState.getCommandResponse()}) .withEventIndexes(new long[]{sessionState.getEventIndex()}) .build(); connection.keepAlive(request).whenComplete((response, error) -> { if (error == null) { if (response.status() == RaftResponse.Status.OK) { future.complete(null); } else { future.completeExceptionally(response.error().createException()); } } else { future.completeExceptionally(error); } }); return future; }
Example #22
Source File: PartitionedDistributedCollectionProxy.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Boolean> addAll(Collection<? extends String> c) { Map<PartitionId, Collection<String>> partitions = Maps.newHashMap(); c.forEach(key -> partitions.computeIfAbsent(getProxyClient().getPartitionId(key), k -> Lists.newArrayList()).add(key)); return Futures.allOf(partitions.entrySet().stream() .map(entry -> getProxyClient() .applyOn(entry.getKey(), service -> service.addAll(entry.getValue())) .thenCompose(result -> checkLocked(result))) .collect(Collectors.toList())) .thenApply(results -> results.stream().reduce(Boolean::logicalOr).orElse(false)); }
Example #23
Source File: AbstractProxyClient.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<Void> delete() { return Futures.allOf(partitions.values() .stream() .map(ProxySession::delete) .collect(Collectors.toList())) .thenApply(v -> null); }
Example #24
Source File: TestMessagingService.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<byte[]> sendAndReceive(Address address, String type, byte[] payload, boolean keepAlive, Executor executor) { if (isPartitioned(address)) { return Futures.exceptionalFuture(new ConnectException()); } ComposableFuture<byte[]> future = new ComposableFuture<>(); sendAndReceive(address, type, payload).whenCompleteAsync(future, executor); return future; }
Example #25
Source File: GossipDistributedValue.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<V> get() { try { return CompletableFuture.completedFuture(value.get()); } catch (Exception e) { return Futures.exceptionalFuture(e); } }
Example #26
Source File: TestMessagingService.java From atomix with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<byte[]> sendAndReceive(Address address, String type, byte[] payload, boolean keepAlive, Executor executor) { if (isPartitioned(address)) { return Futures.exceptionalFuture(new ConnectException()); } ComposableFuture<byte[]> future = new ComposableFuture<>(); sendAndReceive(address, type, payload).whenCompleteAsync(future, executor); return future; }
Example #27
Source File: LocalRaftServerProtocol.java From zeppelin with Apache License 2.0 | 5 votes |
CompletableFuture<byte[]> poll(byte[] request) { if (pollHandler != null) { return pollHandler.apply(decode(request)).thenApply(this::encode); } else { return Futures.exceptionalFuture(new ConnectException()); } }
Example #28
Source File: LocalRaftServerProtocol.java From atomix with Apache License 2.0 | 5 votes |
CompletableFuture<byte[]> keepAlive(byte[] request) { if (keepAliveHandler != null) { return keepAliveHandler.apply(decode(request)).thenApply(this::encode); } else { return Futures.exceptionalFuture(new ConnectException()); } }
Example #29
Source File: LocalRaftServerProtocol.java From zeppelin with Apache License 2.0 | 5 votes |
CompletableFuture<byte[]> reconfigure(byte[] request) { if (reconfigureHandler != null) { return reconfigureHandler.apply(decode(request)).thenApply(this::encode); } else { return Futures.exceptionalFuture(new ConnectException()); } }
Example #30
Source File: LocalRaftServerProtocol.java From zeppelin with Apache License 2.0 | 5 votes |
CompletableFuture<byte[]> join(byte[] request) { if (joinHandler != null) { return joinHandler.apply(decode(request)).thenApply(this::encode); } else { return Futures.exceptionalFuture(new ConnectException()); } }