Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asynchronous function calls in Java

Suppose you have three classes A,B,C each having its own search function. I want to run a key ( say 'searchKey' ) concurrently using all the three search functions. How do I stop the other two search functions if I get the result from one of the three functions ?

Also would this run faster than the case where I have a distinct hashmap in each class and search them one after the other since the search resolves to a constant time complexity ?

like image 908
EmperorPenguin Avatar asked Nov 29 '18 10:11

EmperorPenguin


People also ask

What is synchronous and asynchronous calls in Java?

Synchronous (Sync) and asynchronous (Async) programming can be done in one or multiple threads. The main difference between the two is when using synchronous programming we can execute one task at a time, but when using asynchronous programming we can execute multiple tasks at the same time.

What is an asynchronous call?

An asynchronous method call is a method used in . NET programming that returns to the caller immediately before the completion of its processing and without blocking the calling thread.

What is asynchronous process in Java?

Asynchronous processing refers to assigning these blocking operations to a new thread and retuning the thread associated with the request immediately to the container.

How do you make a method asynchronous in Java?

We can use the submit method of the ExecutorService to perform the task asynchronously and return the instance of the FutureTask. Here we've used the isDone method provided by the Future interface to check if the task is completed. Once finished, we can retrieve the result using the get method.


1 Answers

You would need to expose a public method to stop the search e.g. a flag to cancel the Threads in their respective class.

To your second point, the time complexity for a key search in a HashMap is usually O(1) (worst case O(n) if those keys are in the same hash bucket). So there is not much room for optimization since it's already blazing fast. You would not even notice that if you are searching the HashMaps in sequence.

like image 125
Murat Karagöz Avatar answered Sep 21 '22 12:09

Murat Karagöz