CompletableFuture

 

CompletableFuture is used for asynchronous or non-blocking programming in Java. With asynchronous programming, you can have one or many tasks being processed at the same time. This is done by using separate threads, other than the main thread, to process other tasks. The main thread is not blocked or waiting so tasks can be done in parallel. The main thread is just notified when other threads are done with their tasks whether it’s completion or failure.

A Future is used as a reference to the result of an asynchronous computation. It provides an isDone() method to check whether the computation is done or not, and a get() method to retrieve the result of the computation when it is done.

 

CompletableFuture<String> realName = restService.getName();
		
try {
	log.info("sleeping 1000 millseconds");
		
	TimeUnit.SECONDS.sleep(5);
	if (realName.isDone()) {
		log.info("yeah here is your realname={}", realName.get());
	}else {
		log.info("nah realname has not found yet");
	}
} catch (InterruptedException | ExecutionException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
}

 

 

 

		CompletableFuture<ArrayNode> plUsers = restService.getPlaceHolderTestingList(RestService.PLACEHOLDER_USER);
		
		CompletableFuture<ArrayNode> plTodos = restService.getPlaceHolderTestingList(RestService.PLACEHOLDER_TODO);
		
		CompletableFuture<ArrayNode> plComments = restService.getPlaceHolderTestingList(RestService.PLACEHOLDER_COMMENT);
		
		CompletableFuture<ArrayNode> plPhotos = restService.getPlaceHolderTestingList(RestService.PLACEHOLDER_PHOTO);
		
		CompletableFuture.allOf(plUsers,plTodos,plComments,plPhotos).join();
		
		try {
			log.info("plUsers={}",ObjectUtils.toJson(plUsers.get()));
			log.info("plTodos={}",ObjectUtils.toJson(plTodos.get()));
			log.info("plComments={}",ObjectUtils.toJson(plComments.get()));
			log.info("plPhotos={}",ObjectUtils.toJson(plPhotos.get()));
			
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 

 

		List<String> placeHolders = Arrays.asList(RestService.PLACEHOLDER_USER, RestService.PLACEHOLDER_TODO);

		CompletableFuture<ArrayNode>[] futures = new CompletableFuture[placeHolders.size()];

		for (int i = 0; i < futures.length; i++) {
			CompletableFuture<ArrayNode> pl = restService.getPlaceHolderTestingList(placeHolders.get(i));
			futures[i] = pl;
		}

		CompletableFuture.allOf(futures).join();

		try {
			for (int i = 0; i < futures.length; i++) {
				ArrayNode plhds = futures[0].get();
				log.info("plhds={}", ObjectUtils.toJson(plhds));
			}

		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *