Suppose I have this code:
public HttpResponse myFunction(...) {
final HttpResponse resp;
OnResponseCallback myCallback = new OnResponseCallback() {
public void onResponseReceived(HttpResponse response) {
resp = response;
}
};
// launch operation, result will be returned to myCallback.onResponseReceived()
// wait on a CountDownLatch until operation is finished
return resp;
}
Obviously I can not assign a value to resp from onResponseReceived because it is a final variable, BUT if it was not a final variable onResponseReceived could not see it.
Then, how can I assign a value to resp from onResponseReceived?
What I thought is to create a wrapper class for enclosing the resp object. The final object would be an instance of this wrapper class and I could assign the value to resp working on the object inside the final class (which is not final).
The code would be this one:
class ResponseWrapper {
HttpResponse resp = null;
}
public HttpResponse myFunction(...) {
final ResponseWrapper respWrap = new ResponseWrapper();
OnResponseCallback myCallback = new OnResponseCallback() {
public void onResponseReceived(HttpResponse response) {
respWrap.resp = response;
}
};
// launch operation, result will be returned to myCallback.onResponseReceived()
// wait on a CountDownLatch until operation is finished
return respWrap.resp;
}
What do you think about this solution?
java.util.concurrent.atomic.AtomicReference
Standard practice is to use a final AtomicReference, which you can set and get. This adds the benefit of thread safety as well 🙂 As you mentioned, a CountDownLatch is helpful in waiting for completion.