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 ?
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.
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.
Asynchronous processing refers to assigning these blocking operations to a new thread and retuning the thread associated with the request immediately to the container.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With