Junior — Middle
What methods can be used to organize a response waiting mechanism in software systems?
sobes.tech AI
Answer from AI
In Java, there are several ways to implement a wait-for-response mechanism:
-
Using wait() and notify()/notifyAll() methods — a classic way of thread synchronization through an object's monitor. A thread calls
wait()to suspend execution until notified. -
Classes from java.util.concurrent:
- CountDownLatch — allows one or more threads to wait until a certain number of operations have completed.
- CyclicBarrier — allows a group of threads to wait for each other.
- Future and CompletableFuture — enable asynchronous result retrieval and waiting for its completion.
-
The join() method — a thread calls
join()on another thread to wait for its completion. -
Synchronization via locks (Lock, Condition) — a more flexible way to manage waiting and notification.
Example with CompletableFuture:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Long operation
return "Result";
});
// Waiting for the result
String result = future.get();
System.out.println(result);