scala.concurrent.Await Java Examples

The following examples show how to use scala.concurrent.Await. 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: SshClientActor.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object message) throws Throwable {
    if (message instanceof ReceiveTimeout) {
        sshClientService.onSessionCreateTimeout(clientId);
        self().tell(PoisonPill.getInstance(), self());
    } else if (message instanceof SessionCreateResponse) {
        SessionCreateResponse sessionCreateResponse = (SessionCreateResponse)message;
        LOG.info("looking for session actor: {}", sessionCreateResponse.getSessionActorAddress());
        Future<ActorRef> actorRefFuture = context().system()
                .actorSelection(sessionCreateResponse.getSessionActorAddress()).resolveOne(Timeout.apply(2, TimeUnit.SECONDS));
        sshSessionActor = Await.result(actorRefFuture, Duration.apply(2, TimeUnit.SECONDS));
        sshClientService.onSessionCreateReply(sessionCreateResponse.getClientId(), sessionCreateResponse.getSessionId(), sshSessionActor, sessionCreateResponse.getSessionActorAddress());
    } else if (message instanceof SessionDataResponse) {
        SessionDataResponse sessionDataResponse = (SessionDataResponse)message;
        sshClientService.onSessionDataReceived(clientId, sessionDataResponse);
    } else if (message instanceof SessionCloseResponse) {
        SessionCloseResponse sessionCloseResponse = (SessionCloseResponse)message;
        sshClientService.onCloseSessionResponse(clientId, sessionCloseResponse);
        self().tell(PoisonPill.getInstance(), self());
    } else {
        LOG.info("onReceive: {}", message.getClass().getName());
    }
}
 
Example #2
Source File: LeaderRetrievalUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the leader akka url and the current leader session ID. The values are stored in a
 * {@link LeaderConnectionInfo} instance.
 *
 * @param leaderRetrievalService Leader retrieval service to retrieve the leader connection
 *                               information
 * @param timeout Timeout when to give up looking for the leader
 * @return LeaderConnectionInfo containing the leader's akka URL and the current leader session
 * ID
 * @throws LeaderRetrievalException
 */
public static LeaderConnectionInfo retrieveLeaderConnectionInfo(
		LeaderRetrievalService leaderRetrievalService,
		FiniteDuration timeout
) throws LeaderRetrievalException {
	LeaderConnectionInfoListener listener = new LeaderConnectionInfoListener();

	try {
		leaderRetrievalService.start(listener);

		Future<LeaderConnectionInfo> connectionInfoFuture = listener.getLeaderConnectionInfoFuture();

		return Await.result(connectionInfoFuture, timeout);
	} catch (Exception e) {
		throw new LeaderRetrievalException("Could not retrieve the leader address and leader " +
				"session ID.", e);
	} finally {
		try {
			leaderRetrievalService.stop();
		} catch (Exception fe) {
			LOG.warn("Could not stop the leader retrieval service.", fe);
		}
	}
}
 
Example #3
Source File: LeaderRetrievalUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the current leader gateway using the given {@link LeaderRetrievalService}. If the
 * current leader could not be retrieved after the given timeout, then a
 * {@link LeaderRetrievalException} is thrown.
 *
 * @param leaderRetrievalService {@link LeaderRetrievalService} which is used for the leader retrieval
 * @param actorSystem ActorSystem which is used for the {@link LeaderRetrievalListener} implementation
 * @param timeout Timeout value for the retrieval call
 * @return The current leader gateway
 * @throws LeaderRetrievalException If the actor gateway could not be retrieved or the timeout has been exceeded
 */
public static ActorGateway retrieveLeaderGateway(
		LeaderRetrievalService leaderRetrievalService,
		ActorSystem actorSystem,
		FiniteDuration timeout)
	throws LeaderRetrievalException {
	LeaderGatewayListener listener = new LeaderGatewayListener(actorSystem, timeout);

	try {
		leaderRetrievalService.start(listener);

		Future<ActorGateway> actorGatewayFuture = listener.getActorGatewayFuture();

		return Await.result(actorGatewayFuture, timeout);
	} catch (Exception e) {
		throw new LeaderRetrievalException("Could not retrieve the leader gateway.", e);
	} finally {
		try {
			leaderRetrievalService.stop();
		} catch (Exception fe) {
			LOG.warn("Could not stop the leader retrieval service.", fe);
		}
	}
}
 
Example #4
Source File: AkkaRpcActorTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that actors are properly terminated when the AkkaRpcService is shut down.
 */
@Test
public void testActorTerminationWhenServiceShutdown() throws Exception {
	final ActorSystem rpcActorSystem = AkkaUtils.createDefaultActorSystem();
	final RpcService rpcService = new AkkaRpcService(
		rpcActorSystem, AkkaRpcServiceConfiguration.defaultConfiguration());

	try {
		SimpleRpcEndpoint rpcEndpoint = new SimpleRpcEndpoint(rpcService, SimpleRpcEndpoint.class.getSimpleName());

		rpcEndpoint.start();

		CompletableFuture<Void> terminationFuture = rpcEndpoint.getTerminationFuture();

		rpcService.stopService();

		terminationFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
	} finally {
		rpcActorSystem.terminate();
		Await.ready(rpcActorSystem.whenTerminated(), FutureUtils.toFiniteDuration(timeout));
	}
}
 
Example #5
Source File: ClusterClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Cancels a job identified by the job id and triggers a savepoint.
 * @param jobId the job id
 * @param savepointDirectory directory the savepoint should be written to
 * @return path where the savepoint is located
 * @throws Exception In case an error occurred.
 */
public String cancelWithSavepoint(JobID jobId, @Nullable String savepointDirectory) throws Exception {
	final ActorGateway jobManager = getJobManagerGateway();

	Object cancelMsg = new JobManagerMessages.CancelJobWithSavepoint(jobId, savepointDirectory);

	Future<Object> response = jobManager.ask(cancelMsg, timeout);
	final Object rc = Await.result(response, timeout);

	if (rc instanceof JobManagerMessages.CancellationSuccess) {
		JobManagerMessages.CancellationSuccess success = (JobManagerMessages.CancellationSuccess) rc;
		return success.savepointPath();
	} else if (rc instanceof JobManagerMessages.CancellationFailure) {
		throw new Exception("Cancel & savepoint for the job with ID " + jobId + " failed.",
			((JobManagerMessages.CancellationFailure) rc).cause());
	} else {
		throw new IllegalStateException("Unexpected response: " + rc);
	}
}
 
Example #6
Source File: ClusterClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Stops a program on Flink cluster whose job-manager is configured in this client's configuration.
 * Stopping works only for streaming programs. Be aware, that the program might continue to run for
 * a while after sending the stop command, because after sources stopped to emit data all operators
 * need to finish processing.
 *
 * @param jobId
 *            the job ID of the streaming program to stop
 * @throws Exception
 *             If the job ID is invalid (ie, is unknown or refers to a batch job) or if sending the stop signal
 *             failed. That might be due to an I/O problem, ie, the job-manager is unreachable.
 */
public void stop(final JobID jobId) throws Exception {
	final ActorGateway jobManager = getJobManagerGateway();

	Future<Object> response = jobManager.ask(new JobManagerMessages.StopJob(jobId), timeout);

	final Object rc = Await.result(response, timeout);

	if (rc instanceof JobManagerMessages.StoppingSuccess) {
		// no further action required
	} else if (rc instanceof JobManagerMessages.StoppingFailure) {
		throw new Exception("Stopping the job with ID " + jobId + " failed.",
			((JobManagerMessages.StoppingFailure) rc).cause());
	} else {
		throw new IllegalStateException("Unexpected response: " + rc);
	}
}
 
Example #7
Source File: ClusterClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Requests and returns the accumulators for the given job identifier. Accumulators can be
 * requested while a is running or after it has finished.
 * @param jobID The job identifier of a job.
 * @param loader The class loader for deserializing the accumulator results.
 * @return A Map containing the accumulator's name and its value.
 */
public Map<String, OptionalFailure<Object>> getAccumulators(JobID jobID, ClassLoader loader) throws Exception {
	ActorGateway jobManagerGateway = getJobManagerGateway();

	Future<Object> response;
	try {
		response = jobManagerGateway.ask(new RequestAccumulatorResults(jobID), timeout);
	} catch (Exception e) {
		throw new Exception("Failed to query the job manager gateway for accumulators.", e);
	}

	Object result = Await.result(response, timeout);

	if (result instanceof AccumulatorResultsFound) {
		Map<String, SerializedValue<OptionalFailure<Object>>> serializedAccumulators =
				((AccumulatorResultsFound) result).result();

		return AccumulatorHelper.deserializeAccumulators(serializedAccumulators, loader);

	} else if (result instanceof AccumulatorResultsErroneous) {
		throw ((AccumulatorResultsErroneous) result).cause();
	} else {
		throw new Exception("Failed to fetch accumulators for the job " + jobID + ".");
	}
}
 
Example #8
Source File: LeaderRetrievalUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the leader akka url and the current leader session ID. The values are stored in a
 * {@link LeaderConnectionInfo} instance.
 *
 * @param leaderRetrievalService Leader retrieval service to retrieve the leader connection
 *                               information
 * @param timeout Timeout when to give up looking for the leader
 * @return LeaderConnectionInfo containing the leader's akka URL and the current leader session
 * ID
 * @throws LeaderRetrievalException
 */
public static LeaderConnectionInfo retrieveLeaderConnectionInfo(
		LeaderRetrievalService leaderRetrievalService,
		FiniteDuration timeout
) throws LeaderRetrievalException {
	LeaderConnectionInfoListener listener = new LeaderConnectionInfoListener();

	try {
		leaderRetrievalService.start(listener);

		Future<LeaderConnectionInfo> connectionInfoFuture = listener.getLeaderConnectionInfoFuture();

		return Await.result(connectionInfoFuture, timeout);
	} catch (Exception e) {
		throw new LeaderRetrievalException("Could not retrieve the leader address and leader " +
				"session ID.", e);
	} finally {
		try {
			leaderRetrievalService.stop();
		} catch (Exception fe) {
			LOG.warn("Could not stop the leader retrieval service.", fe);
		}
	}
}
 
Example #9
Source File: AkkaRpcActorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that actors are properly terminated when the AkkaRpcService is shut down.
 */
@Test
public void testActorTerminationWhenServiceShutdown() throws Exception {
	final ActorSystem rpcActorSystem = AkkaUtils.createDefaultActorSystem();
	final RpcService rpcService = new AkkaRpcService(
		rpcActorSystem, AkkaRpcServiceConfiguration.defaultConfiguration());

	try {
		SimpleRpcEndpoint rpcEndpoint = new SimpleRpcEndpoint(rpcService, SimpleRpcEndpoint.class.getSimpleName());

		rpcEndpoint.start();

		CompletableFuture<Void> terminationFuture = rpcEndpoint.getTerminationFuture();

		rpcService.stopService();

		terminationFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
	} finally {
		rpcActorSystem.terminate();
		Await.ready(rpcActorSystem.whenTerminated(), FutureUtils.toFiniteDuration(timeout));
	}
}
 
Example #10
Source File: AkkaTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsk(final MockTracer tracer) throws Exception {
  final ActorRef actorRef = system.actorOf(TestActor.props(tracer, false), "ask");
  final Timeout timeout = new Timeout(getDefaultDuration());

  final Future<Object> future = ask(actorRef, "ask", timeout);
  final Boolean isSpanNull = (Boolean)Await.result(future, getDefaultDuration());
  assertFalse(isSpanNull);

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
  for (final MockSpan span : spans)
    assertEquals(AkkaAgentIntercept.COMPONENT_NAME, span.tags().get(Tags.COMPONENT.getKey()));
}
 
Example #11
Source File: AkkaTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testForward(final MockTracer tracer) throws Exception {
  final ActorRef actorRef = system.actorOf(TestActor.props(tracer, true), "forward");
  final Timeout timeout = new Timeout(getDefaultDuration());

  final Future<Object> future = ask(actorRef, "forward", timeout);
  final Boolean isSpanNull = (Boolean)Await.result(future, getDefaultDuration());
  assertFalse(isSpanNull);

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
  for (final MockSpan span : spans)
    assertEquals(AkkaAgentIntercept.COMPONENT_NAME, span.tags().get(Tags.COMPONENT.getKey()));
}
 
Example #12
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensureConstN() throws Exception {
  Future<Void> f = constVoidFuture;
  for (int i = 0; i < N.n; i++)
    f.transform(ensureF, ec);
  return Await.result(f, inf);
}
 
Example #13
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #14
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromiseN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.flatMap(flatMapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example #15
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromise() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future().flatMap(flatMapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example #16
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String setValueN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example #17
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #18
Source File: DefaultQuarantineHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void shutdownActorSystem(ActorSystem actorSystem) {
	// shut the actor system down
	actorSystem.terminate();

	try {
		// give it some time to complete the shutdown
		Await.ready(actorSystem.whenTerminated(), timeout);
	} catch (InterruptedException | TimeoutException e) {
		log.error("Exception thrown when terminating the actor system", e);
	} finally {
		// now let's crash the JVM
		System.exit(exitCode);
	}
}
 
Example #19
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromise() throws Exception {
  Promise<Void> p = Promise.<Void>apply();
  Future<Void> f = p.future().transform(ensureF, ec);
  p.success(null);
  return Await.result(f, inf);
}
 
Example #20
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapConstN() throws Exception {
  Future<String> f = constFuture;
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF, ec);
  return Await.result(f, inf);
}
 
Example #21
Source File: SearchTelemetryGenerator.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private void generateTelemetry(Request request) {
  Future<Response> response = (Future<Response>) request.getRequest().get("searchFResponse");
  String indexType = (String) request.getRequest().get("indexType");
  SearchDTO searchDto = (SearchDTO) request.getRequest().get("searchDto");
  Map<String, Object> telemetryContext =
      (Map<String, Object>) request.getRequest().get("context");
  Response orgSearchResponse = null;
  try {
    orgSearchResponse = Await.result(response, BaseActor.timeout.duration());
    String[] types = new String[] {indexType};
    Map<String, Object> contentMap = new HashMap<>();
    List<Object> contentList = new ArrayList<>();
    if (orgSearchResponse != null
        && MapUtils.isNotEmpty(orgSearchResponse.getResult())
        && MapUtils.isNotEmpty(
            (Map<String, Object>) orgSearchResponse.getResult().get(JsonKey.RESPONSE))) {
      HashMap<String, Object> contentListMap =
          (HashMap<String, Object>) orgSearchResponse.getResult().get(JsonKey.RESPONSE);
      contentList.add(contentListMap.get(JsonKey.CONTENT));
      if (CollectionUtils.isNotEmpty(contentList)) {
        contentMap.put(JsonKey.CONTENT, contentList.get(0));
        contentMap.put(
            JsonKey.COUNT,
            contentListMap.get(JsonKey.COUNT) != null ? contentListMap.get(JsonKey.COUNT) : 0);
        generateSearchTelemetryEvent(searchDto, types, contentMap, telemetryContext);
      }
    }
  } catch (Exception e) {
    ProjectLogger.log(
        "SearchTelemetryGenerator:generateTelemetry: Error occured in generating Telemetry for orgSearch  ",
        e,
        LoggerEnum.ERROR.name());
  }
}
 
Example #22
Source File: InterServiceCommunicationImpl.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Override
public Object getResponse(ActorRef actorRef, Request request) {
  try {
    return Await.result(getFuture(actorRef, request), t.duration());
  } catch (Exception e) {
    ProjectLogger.log(
        "InterServiceCommunicationImpl:getResponse: Exception occurred with error message = "
            + e.getMessage(),
        e);
    ProjectCommonException.throwServerErrorException(
        ResponseCode.unableToCommunicateWithActor,
        ResponseCode.unableToCommunicateWithActor.getErrorMessage());
  }
  return null;
}
 
Example #23
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #24
Source File: Calculator.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
public static void awaitTermination(final ActorSystem actorSystem) {
	try {
		Await.ready(actorSystem.whenTerminated(), Duration.Inf());
	} catch (TimeoutException | InterruptedException e) {
		e.printStackTrace();
		System.exit(-1);
	}
	System.out.println("ActorSystem terminated!");
}
 
Example #25
Source File: OctopusSystem.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
protected static ActorSystem createSystem(String actorSystemName, Config config) {
	
	// Create the ActorSystem
	final ActorSystem system = ActorSystem.create(actorSystemName, config);
	
	// Register a callback that ends the program when the ActorSystem terminates
	system.registerOnTermination(new Runnable() {
		@Override
		public void run() {
			System.exit(0);
		}
	});
	
	// Register a callback that terminates the ActorSystem when it is detached from the cluster
	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
	
	return system;
}
 
Example #26
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #27
Source File: JobDeployer.java    From AthenaX with Apache License 2.0 5 votes vote down vote up
private void stopAfterJob(ClusterClient client, JobID jobID) {
  Preconditions.checkNotNull(jobID, "The job id must not be null");
  try {
    Future<Object> replyFuture =
        client.getJobManagerGateway().ask(
            new ShutdownClusterAfterJob(jobID),
            AKKA_TIMEOUT);
    Await.ready(replyFuture, AKKA_TIMEOUT);
  } catch (Exception e) {
    throw new RuntimeException("Unable to tell application master to stop"
        + " once the specified job has been finished", e);
  }
}
 
Example #28
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #29
Source File: AkkaSource.java    From flink-learning with Apache License 2.0 5 votes vote down vote up
@Override
public void run(SourceFunction.SourceContext<Object> ctx) throws Exception {
    LOG.info("Starting the Receiver actor {}", actorName);
    receiverActor = receiverActorSystem.actorOf(
            Props.create(classForActor, ctx, urlOfPublisher, autoAck), actorName);

    LOG.info("Started the Receiver actor {} successfully", actorName);
    Await.result(receiverActorSystem.whenTerminated(), Duration.Inf());
}
 
Example #30
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapPromise() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future().map(mapF, ec);
  p.success(string);
  return Await.result(f, inf);
}