I am having hard time converting old fashioned wait notify with spurious waits to java.util.concurrent API
First Problem: What to use, Future or CountdownLatch or CyclicBarrier according to this question
Second Question: How to use it? Because in all the examples I have looked at are converting a single async method to sync which is not a problem
Thirdly: What is the best option in my case out of Future task's get method, CountDownLatch or CyclicBarrier, since I dont have multiple threads, but only 2.
My async code
Main class:
public static void main(String[] args) throws InterruptedException {
Request req = new Request(1);
Thread tReq = new Thread(req);
tReq.start();
synchronized(req){
req.wait();
}
LogProperties.log.info("Response is: " + req.responseString);
}
Request Class:
public class Request implements Runnable {
private int requestID;
public boolean isComplete;
public String responseString;
public Request(int id) {
this.requestID = id;
}
@Override
public void run() {
FutureTest.hmTest.put(requestID, this);
try {
//simulate a request
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
Response response = new Response(requestID);
Thread tResponse = new Thread(response);
tResponse.start();
}
}
Response Class:
public class Response implements Runnable {
int id;
public Response(int responseId) {
this.id = responseId;
}
@Override
public void run() {
Request req = (Request) FutureTest.hmTest.get(id);
req.isComplete = true;
req.responseString = "Request for id [" + id + "] has been completed";
synchronized(req){
req.notify();
}
}
}
My Problem with using future callable and CyclicBarrier is that Im not returning a variable, I want to wait on a object, which is of type Request in this case, so what is the best solution