# How to synchronize current thread with SubmitAsyncSearchRequest?

**URL:** <https://discuss.elastic.co/t/how-to-synchronize-current-thread-with-submitasyncsearchrequest/253795>\
**Category:** Elasticsearch\
**Created:** [October 30, 2020, 10:18am UTC](https://discuss.elastic.co/t/how-to-synchronize-current-thread-with-submitasyncsearchrequest/253795 "2020-10-30T10:18:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Woniok](https://avatars.discourse-cdn.com/v4/letter/w/3da27b/32.png) [@Woniok](https://discuss.elastic.co/u/Woniok)\
**Post date:** [October 30, 2020, 10:18am UTC](https://discuss.elastic.co/t/how-to-synchronize-current-thread-with-submitasyncsearchrequest/253795/1 "2020-10-30T10:18:19Z")

</div>

Hi, guys. Thank you for building such wonderful tools. 😀

While I was coding with the guidance of the `[SubmitAsyncSearchRequest document](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-asyncsearch-asyncsearch-submit.html)`, I didn't know what to do in order to wait for the response from the current thread in the context as below.

```auto
    @Async
	@CrossOrigin  
	@GetMapping(path="/my/path/{docId}")
	public @ResponseBody ResponseEntity<Result> getAsyncResult(
		@PathVariable Integer docId
	) {
		ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("localhost:9200").build();
        RestHighLevelClient client = RestClients.create(clientConfiguration).rest();

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		SearchSourceBuilder searchSource = searchSourceBuilder.query(QueryBuilders.matchQuery("_id", docId));
		String[] indices = new String[] {"my_index"};
		SubmitAsyncSearchRequest request
			= new SubmitAsyncSearchRequest(searchSource, indices);

		request.setWaitForCompletionTimeout(TimeValue.timeValueSeconds(1));
		request.setKeepAlive(TimeValue.timeValueDays(365));
		request.setKeepOnCompletion(true);
		
		AsyncSearchClient asyncClient = client.asyncSearch();
		Result result = new Result();

		ActionListener<AsyncSearchResponse> actionListner
			 = new ActionListener<AsyncSearchResponse>() {
				 @Override
				 public void onResponse(AsyncSearchResponse response) {
					if (response.isPartial() == true) {
						logger.info("The response is PARTIAL!");
					} else {
						logger.info("The response is COMPLETE!");
					}

					SearchResponse searchResponse = response.getSearchResponse();
					if (searchResponse != null) {
						SearchHit[] searchHits = searchResponse.getHits().getHits();

						int numHits = searchHits.length;
						logger.info(" ******* No. hits: " + numHits);

						if (numHits > 0) {
							for (int i=0; i<numHits; i++) {
								logger.info("[" + i + "] : " + searchHits[i].getId());

								String jsonString = searchHits[i].getSourceAsString();

								logger.info(">>> The raw string: " + jsonString);
								
// SOME BUSINESS LOGIC filling `result`.

							}	// END: for (~)
							logger.info(" ******* ABOVE: Hit IDs");
						}	// END: if (numHits > 0)
					}	// END: if (searchResponse != null)
				 }	// END: public void onResponse(AsyncSearchResponse response)

				 @Override
				 public void onFailure(Exception e) {
					String expMsg = e.getMessage();
					logger.error("Async Request Failed for error: " + expMsg);
				 }	// END: public void onFailure(Exception e)
			 }; // END: new ActionListener<AsyncSearchResponse>(){}
		
		Cancellable cancellable = asyncClient.submitAsync(request, RequestOptions.DEFAULT, actionListner);
		
		// cancellable.cancel();
		
		// TODO: Wait for request to be done. If the onResponse() finishes, then continue to below. 

		ResponseEntity<Result> result0 = null;
		
		result0 = (result.filled() == true) ? new ResponseEntity<Result>(minute, HttpStatus.OK)
		: new ResponseEntity<Result>(HttpStatus.INTERNAL_SERVER_ERROR);

		logger.info("BEFORE RETURNING");

		return result0;
	}

```

According to those log messages, always `BEFORE RETURNING` appears before the ones in `onResponse()`.

But, I want the current thread(?) to wait until `onResponse()` is done.

What am I supposed to do?

Thank you for reading my question and answering in advance! 😄

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [November 27, 2020, 10:18am UTC](https://discuss.elastic.co/t/how-to-synchronize-current-thread-with-submitasyncsearchrequest/253795/2 "2020-11-27T10:18:24Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
